Spring Data JPA - Relational Query - Operating Multi-to-Multi Relational Relations

Keywords: xml

One) Bidirectional multi-to-many configuration

1.1: Configure many-to-many
Requirement roles have multiple menus, and menus belong to multiple roles
Annotation @ManyToMany used

@Target({ElementType.METHOD, ElementType.FIELD})
public @interface ManyToMany {
    Class targetEntity() default void.class; //Target class, referring to the associated target class

    CascadeType[] cascade() default {};//cascade policies

    FetchType fetch() default FetchType.LAZY;//Loading strategy

    String mappedBy() default "";//mapping

Menu entity

@Table(name = "t_menu")
public class Menu {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "menuid")
    private Integer menuid;

    @Column(name = "menuName")
    private String menuName;

    @ManyToMany(mappedBy = "menuSet")
    private Set<Roles> rolesSet = new HashSet<>();

Role entity

Annotation @ManyToMany. @JoinTable
The @JoinTable annotation is the annotation to set up the intermediate table, and the @JoinTable annotation can appear in either of the two parties.
@ JoinTable requires three main attributes
1.name: name of the intermediate table
2. join Columns: The foreign key name of the intermediate table that exists in the current table
3. InverseJoin Columns Another name for a multi-party intermediate table

@Table(name = "t_roles")
public class Roles {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "roleid")
    private Integer roleid;

    @Column(name = "roleName")
    private String roleName;

     * One-to-many configuration
    @OneToMany(mappedBy = "roles",fetch = FetchType.EAGER)
    private Set<Users> usersSet = new HashSet<>();

     * Many-to-many configuration: Annotations can appear in either of two multi-party entities, so in this case, the configuration is reversed from the current configuration.
     * Use the annotation @JoinTable:name: specify the name of the intermediate table
     *                      joinColumns: Current multiparty presence of foreign key names in the middle table
     *                      inverseJoinColumns: The foreign key name of another party that exists in the middle table
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "role_menu",joinColumns = @JoinColumn(name = "role_id"),inverseJoinColumns = @JoinColumn(name = "menu_id"))
    private Set<Menu> menuSet = new HashSet<>();


public class TestManyToMany {

    private RoleDao roleDao;

    public void test2(){
        Roles one = this.roleDao.findOne(5);

    public void test1(){
        Roles roles = new Roles();

        Menu menu = new Menu();

        Menu menu1 = new Menu();

        //Establish relationship


        //Action menu through role Association

Posted by NTFS on Mon, 30 Sep 2019 23:56:27 -0700