1. 程式人生 > 實用技巧 >jpa 多對多關聯關係

jpa 多對多關聯關係

1. user  主控方
@Getter
@Setter
@Entity
@Table(name = "t_user")
@NoArgsConstructor
public class User {

@Id
private Long id;

private String username;

public User(Long id, String username) {
this.id = id;
this.username = username;
}


/**
* 所屬的角色
*/
@ManyToMany
@JoinTable(name = "mt_sys_user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();

}


2. role ,不控制關聯關係。
@Getter
@Setter
@Entity
@Table(name = "t_role")
@NoArgsConstructor
public class Role {

@Id
private Long id;

private String roleName;

public Role(Long id, String roleName) {
this.id = id;
this.roleName = roleName;
}

/**
* 角色所包含的使用者
*/
@ManyToMany(mappedBy = "roles")
private Set<User> users = new HashSet<>();
}
3.初始化資料
Role role1 = new Role(1L, "role1");
Role role2 = new Role(2L, "role2");
Role role3 = new Role(3L, "role3");
this.roleRepository.save(role1);
this.roleRepository.save(role2);
this.roleRepository.save(role3);

User user1 = new User(1L, "user1");
User user2 = new User(2L, "user2");
User user3 = new User(3L, "user3");
this.userRepository.save(user1);
this.userRepository.save(user2);
this.userRepository.save(user3);
4.建立關聯關係
在主控方加入即可,此時 user 和 role 都是受管狀態。
User user = this.userRepository.findById(1L).orElse(null);
Role role = this.roleRepository.findById(1L).orElse(null);
user.getRoles().add(role);