您需要一个关联表,通常出于各种原因通常在JPA中构建该关联表,主要是为了控制表中的内容,或者在这种情况下映射n路M:N关系。
创建所有实体:
@Entitypublic class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; private String userName; @oneToMany(mappedBy="user") private Set<UserDepartmentRoleAssociation> associations;... etc}和
@Entitypublic class Department { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; private String department; @oneToMany(mappedBy="department") private Set<UserDepartmentRoleAssociation> associations; ... etc}和
@Entitypublic class Role { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; private String role; ... etc}并创建关联表和ID类。
@Entitypublic 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}和
@Embeddablepublic 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在读取记录时创建的。



