简体   繁体   English

插入多对多的一张表并加入表休眠

[英]Insert into one table of ManytoMany and joining table hibernate

在此处输入图片说明

Hi I am new to Hibernate and trying to build a Rest APP.嗨,我是 Hibernate 的新手,正在尝试构建一个 Rest APP。

I have 3 tables in the database as shown in the above image.如上图所示,我在数据库中有 3 个表。

USERS table has ManyToMany relation with GROUPS table and USER_GROUP is an association table. USERS 表与 GROUPS 表有 ManyToMany 关系,USER_GROUP 是关联表。

I am using ORM, Hibernate and CurdRepository.我正在使用 ORM、Hibernate 和 CurdRepository。

I am able to insert into users table and group table with save() method of CurdRepository.我可以使用 CurdRepository 的 save() 方法插入到用户表和组表中。

Now I am trying to add a row in GROUPS table and USER_GROUP table only.现在我试图仅在 GROUPS 表和 USER_GROUP 表中添加一行。 Can anyone lead me to the right direction?谁能引导我走向正确的方向?

For example:例如:

I want to add an groupid to GROUPS table and then associate it with an user id我想将 groupid 添加到 GROUPS 表,然后将其与用户 id 相关联

Let's say I want to insert (10) groupid in GROUPS and (14,10) in USER_GROUP table.假设我想在 GROUPS 中插入 (10) groupid,在 USER_GROUP 表中插入 (14,10)。

Is it doable with ORM, if yes how? ORM 是否可行,如果是,如何?

Thanks in advance提前致谢

There are many articles online about exactly this model to showcase how to use Hibernate.网上有很多关于这个模型的文章来展示如何使用 Hibernate。 Here is one article I quickly found by googling for "hibernate user group example": https://www.codejava.net/frameworks/hibernate/hibernate-many-to-many-association-annotations-example这是我通过谷歌搜索“休眠用户组示例”快速找到的一篇文章: https : //www.codejava.net/frameworks/hibernate/hibernate-many-to-many-association-annotations-example

To use existing connecting table, USE_GROUP, User entity will be like following .要使用现有的连接表,USE_GROUP,用户实体将如下所示。

@Entity
public class Users {
    @Id
    private Integer userid;

    private String password;

    @ManyToMany(cascade = { CascadeType.MERGE, CascadeType.PERSIST })
    @JoinTable(name = "USER_GROUP", joinColumns = { @JoinColumn(name = "USERID") }, 
        inverseJoinColumns = { @JoinColumn(name = "GROUPID") })
    private Set<Groups> groups;

    // Getter, Setter
}

And then client code, add new User and Group, will be something like below.然后客户端代码,添加新的用户和组,如下所示。

User user = new User()
// set password , etc
Set<Groups> groups = new HashSet<>();
Group group = new Group();
// set 
groups.add(group);

user.setGroups(groups);

userRepository.save(user);

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

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