简体   繁体   English

如何使用Hibernate管理两个表中的多对多关系

[英]How to Manage a Many-to-Many Relationship in Two Table using Hibernate

I am using hibernate-jpa-2.0-api 1.0.0.Final and hibernate 3.5.5-Final . 我正在使用hibernate-jpa-2.0-api 1.0.0.Finalhibernate 3.5.5-Final

I have User and Role entities each having many-to-many relationships to each other (bidirectional). 我有UserRole实体,每个实体彼此之间具有many-to-many关系(双向)。

The relationships create total four table I have reduce to three tables. 关系创建总共四个表我已减少到三个表。

But still my requirement not fulfilled, I just want to manage the data in two tables. 但仍然没有满足我的要求,我只想管理两个表中的数据。

You can manage it like this: 您可以像这样管理它:

@ManyToMany(cascade = {
        CascadeType.ALL
    })
    @JoinTable(name = "NAME OF YOUR TABLE WHERE RELATIONS ARE STORED",
        joinColumns = @JoinColumn(name = "ID_FIRST_TABLE"),
        inverseJoinColumns = @JoinColumn(name = "ID_SECOND_TABLE")
    )
private Set<Entity> entities;

EDIT: I forgot to mention that you only need to write this only on one of the entities, the other one doesn't need the @JoinTable annotation! 编辑:我忘了提到你只需要在其中一个实体上写这个,另一个不需要@JoinTable注释!

I would say add fetch = FetchType.Lazy , for the lazy loading which is preferred in most of the scenarios, just like below: 我会说添加fetch = FetchType.Lazy ,对于大多数场景中首选的延迟加载,如下所示:

@ManyToMany(cascade = {
        CascadeType.ALL
    }, fetch = FetchType.LAZY)
    @JoinTable(name = "TABLE NAME WHERE RELATIONS ARE STORED",
        joinColumns = @JoinColumn(name = "ID_FIRST_TABLE"),
        inverseJoinColumns = @JoinColumn(name = "ID_SECOND_TABLE")
    )
private Set<Entity> entities;

Every answer here are kinda correct BUT! 这里的每个答案都有点正确但是! your object have to be "recursive". 你的对象必须是“递归的”。

Try this: 尝试这个:

User.java User.java


@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@ToString(exclude = "roles")
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue
    @Column(name = "user_id")
    private Long id;

    @Column
    private String username;

    @ManyToMany(cascade = { CascadeType.ALL })
    @JoinTable(name = "user_role",
            joinColumns = { @JoinColumn(name = "user_id") },
            inverseJoinColumns = { @JoinColumn(name = "role_id") })
    private List<Role> roles = new ArrayList<>();


    /*
    We need to add methods below to make everything work correctly.
    Use them to add or delete roles!!!
     */

    public void addRole(Role role) {
        roles.add(role);
        role.getUsers().add(this);
    }

    public void removeRole(Role role) {
        roles.remove(role);
        role.getRoles().remove(this);
    }

}

Role.java Role.java

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@ToString(exclude = "users")
@Table(name = "role")
public class Role{

    @Id
    @GeneratedValue
    @Column(name = "role_id")
    private Long id;

    @Column
    private String roleName;

    @ManyToMany(mappedBy="roles")
    private List<User> users = new ArrayList<>();

    /*
    We need to add methods below to make everything work correctly
     */

    public void addUser(User user) {
        users.add(user);
        user.getRoles().add(this);
    }

    public void removeUser(User user) {
        users.remove(user);
        user.getRoles().remove(this);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM