You need an association table, often constructed in JPA for various reasons mostly to do with control over what goes in the table or in this case mapping an n-way M:N relationship.
Create all your Entities:
@Entity
public class User {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String userName;
@OneToMany(mappedBy="user")
private Set<UserDepartmentRoleAssociation> associations;
... etc
}
and
@Entity
public class Department {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String department;
@OneToMany(mappedBy="department")
private Set<UserDepartmentRoleAssociation> associations;
... etc
}
and
@Entity
public class Role {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String role;
... etc
}
and create your association table and id class.
@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
}
and
@Embeddable
public class UserDepartmentRoleAssociationId implements Serializable {
private Integer userId;
private Integer departmentId;
private Integer roleId;
... etc
}
and to persist a relationship then ...
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);
and to read it with join fetch then
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();
Note that I have used a Set
instead of a List
in Department
and User
which causes much less problems in these cases. Also, I don't have to create associations
when I persist the relationship because the UserDepartmentRoleAssociation
is the owning entity and therefore does the persisting. The associations
sets are created by JPA when it reads a record.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…