在我的项目中,人员具有基于角色的访问权限。一个人可以在多个部门中工作。
我的角色表
Role_id Role 1 Manager 2 Employee
我的部门表
Departmant_id Departmant 1 Production 2 Research 3 Marketing
我的用户表
User_id User_name 1 Jennifer 2 Kate 3 David
我想要的是一个新表,该表指定哪些人在哪个部门中以及他们在该部门中所扮演的角色。
User_id Departmant_id Role_id x x x
我试过的是
Class User{ @ManyToOne(cascade = CascadeType.ALL) @JoinTable(name = "user_department_role",joinColumns = {@JoinColumn(name = "department_id",referencedColumnName = "department_id"),@JoinColumn(name = "user_id",referencedColumnName = "user_id")}, inverseJoinColumns = {@JoinColumn(name = "role_id")}) private Set<Department> departmentList; }
您需要一个关联表,通常出于各种原因通常在JPA中构建该关联表,主要是为了控制表中的内容,或者在这种情况下映射n路M:N关系。
创建所有实体:
@Entity public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; private String userName; @OneToMany(mappedBy="user") private Set<UserDepartmentRoleAssociation> associations; ... etc }
和
@Entity public class Department { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; private String department; @OneToMany(mappedBy="department") private Set<UserDepartmentRoleAssociation> associations; ... etc }
@Entity public class Role { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; private String role; ... etc }
并创建关联表和ID类。
@Entity public class UserDepartmentRoleAssociation { @EmbeddedId private UserDepartmentRoleAssociationId id; @ManyToOne @MapsId("userId") private User user; @ManyToOne @MapsId("departmentId") private Department department; @ManyToOne @MapsId("roleId") private Role role; public UserDepartmentRoleAssociation() { id = new UserDepartmentRoleAssociationId(); } ... etc }
@Embeddable public class UserDepartmentRoleAssociationId implements Serializable { private Integer userId; private Integer departmentId; private Integer roleId; ... etc }
并保持一段感情然后…
User user = new User(); user.setUserName("user1"); Department department = new Department(); department.setDepartment("department 1"); Role role = new Role(); role.setRole("Manager"); UserDepartmentRoleAssociation association = new UserDepartmentRoleAssociation(); association.setUser(user); association.setDepartment(department); association.setRole(role); em.persist(user); em.persist(department); em.persist(role); em.persist(association);
并通过join fetch读取它
User user = em.createQuery("select u from User u left join fetch u.associations ass left join fetch ass.department left join fetch ass.role where u.id = :id", User.class).setParameter("id", 1).getSingleResult();
请注意,在这些情况下,我使用了in Set而不是Listin Department,User它引起的问题要少得多。另外,associations当我保留关系时,我也不必创建,因为它UserDepartmentRoleAssociation是拥有实体,因此也可以保留。这些associations集是由JPA在读取记录时创建的。
Set
List
Department
User
associations
UserDepartmentRoleAssociation