Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

spring - 2 Foreign Keys Into a New Table from Different Entities Hibernate

In my projecet people has role based access.One person can work at more than one departments.

My Role Table

Role_id Role
1       Manager
2       Employee

My Department Table

Departmant_id Departmant
1             Production
2             Research
3             Marketing

My User Table

User_id User_name
1       Jennifer
2       Kate
3       David

What i want is a new table that specifies which people are in which departmant and what role do they have in that department.

User_id Departmant_id Role_id
x       x             x

What i tried is

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...