Many relationships between tables of 24

Table-many relationship is established by the middle of the table, where the relationship between the user and the middle of the table is a table-many relationship between the table and the role of the middle of the table is one to many

A user may have multiple roles, the user entity class should contain information of a plurality of characters, as follows:

/**
 * 用户的数据模型
 */
@Entity
@Table(name="sys_user")
@Data
public class SysUser implements Serializable {
    
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="user_id")
    private Long userId;
    @Column(name="user_code")
    private String userCode;
    @Column(name="user_name")
    private String userName;
    @Column(name="user_password")
    private String userPassword;
    @Column(name="user_state")
    private String userState;
    
    //多对多关系映射
    @ManyToMany(mappedBy="users")
    private Set<SysRole> roles = new HashSet<SysRole>(0);
}

A plurality of users can be given a role, the role of the entity class should contain information of a plurality of users

/**
 * 角色的数据模型
 */
@Entity
@Table(name="sys_role")
@Data
public class SysRole implements Serializable {
    
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="role_id")
    private Long roleId;
    @Column(name="role_name")
    private String roleName;
    @Column(name="role_memo")
    private String roleMemo;
    
    //多对多关系映射
    @ManyToMany
    @JoinTable(name= "user_role_rel", // the name of the intermediate table
               // intermediate table field associated user_role_rel sys_role table's primary key field role_id 
              joinColumns of JoinColumn @ = {(name = "role_id", the referencedColumnName = "role_id" )},
               // the middle of the table user_role_rel primary key user_id field associated sys_user table 
              inverseJoinColumns of JoinColumn @ = {(name = "user_id", the referencedColumnName = "user_id" )} 
    ) 
    Private the Set <SYSUSER> Users = new new HashSet <SYSUSER> (0 ); 
}

Notes mapping instructions

@ManyToMany 
    effect: many relationship for mapping 
    attributes: 
        Cascade: Cascaded operation is configured. 
        fetch: Configure whether to use lazy loading. 
        targetEntity: Configure the target entity class. Time-many mapping without writing. 

@JoinTable 
    effect: for a configuration intermediate table 
    attributes: 
        Nam: Configuration intermediate table name 
        joinColumns: foreign key field of the intermediate table the current entity class primary key field corresponding table                           
        inverseJoincolumn: primary key field of the intermediate table foreign key field associated with the other tables 
        
@JoinColumn 
    effect: a corresponding relationship between the primary key field and define the foreign key column. 
    Properties: 
        name: Specifies the name of the foreign key fields 
        referencedColumnName: Specifies the name of the primary key field referenced primary table 
        unique: is unique. The default value is not the only 
        nullable: whether to allow empty. The default value allows. 
        insertable: whether to allow insertion. The default value allows. 
        updatable: whether to allow updates. The default value allows. 
        columnDefinition: definition information column.
    @Autowired
     Private UserDao userDao; 
    
    @Autowired 
    Private RoleDao roleDao;
     / ** 
     * Requirements: 
     * Save Users and Roles 
     * Requirements: 
     * Create 2 users and 3 characters 
     * Let the user has the No. 1 No. 1 and No. 2 role (in both directions ) 
     * allows 2 users have the No. 2 and No. 3 role (in both directions) 
     * save users and roles 
     * question: 
     * when saving, the primary key to repeat the error occurs, because all you want to save data due to the middle of the table. 
     * Solution: 
     * let either give up defending the rights of association 
     * / 
    @Test 
    the @Transactional   // open transaction 
    @Rollback ( false ) // set to not roll back 
    public  void the Save () {
         // Create Object
        U1 = SYSUSER new new SYSUSER (); 
        u1.setUserName ( "User 1" ); 
        SysRole r1 = new new SysRole (); 
        r1.setRoleName ( "Role 1" );
         // establish a relationship 
        . U1.getRoles () add (r1 ); 
        r1.getUsers () the Add (U1);. 
        // save 
        roleDao.save (R1); 
        userDao.save (U1); 
    }

In many to many (save), if the two-way relations are set, which means both sides maintain middle of the table, will insert data into the middle of the table, two middle of the table and field as the primary key, so the error, the primary key duplication, save fail to solve the problem: only need to give up the right to maintain in the middle of the table can be either recommended in a passive party to give up, configuration is as follows:

// give up the right to maintain the middle of the table, the primary key to solve the preservation problem of conflict 
    @ManyToMany (the mappedBy = "the Roles" )
     Private the Set <SYSUSER> the Users = new new HashSet <SYSUSER> (0);

Deletion

@Autowired
     Private UserDao userDao;
     / ** 
     * delete 
     * When deleting many to many, two-way configuration cascade delete can not 
     * disable 
     * If equipped, and if there is mutual relationship between data references, you may clear all data 
     * / 
    @Test 
    @Transactional 
    @Rollback ( to false ) // set not rollback 
    public  void TestDelete () { 
        userDao.delete ( 1L ); 
    }

 

  

Guess you like

Origin www.cnblogs.com/zhaochengf/p/12127921.html