简体   繁体   English

使用Spring Boot将数据插入到关系表中(多对多)

[英]Insert data into relationship table (many-to-many) with Spring boot

I made a Spring Boot application which contains some users. 我制作了一个包含一些用户的Spring Boot应用程序。 These users can belong to 0, one or many groups (I omitted some lines of code for a better visualisation): 这些用户可以属于0个,一个或多个组(为了更好地显示,我省略了一些代码行):

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany
    @JoinTable(
            name = "group_user",
            joinColumns = {@JoinColumn(name = "user_id")},
            inverseJoinColumns = {@JoinColumn(name = "group_id")}
    )
    private List<Group> groups = new ArrayList<>();

    public User(String name, List<Group> groups) {
        this.name = name;
        this.groups = groups;
    }
}

A group can contain 0, one or many users. 一组可以包含0个,一个或多个用户。

@Entity
public class Group {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

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

    public Group(String name, List<User> users) {
        this.name = name;
        this.users = users;
    }
}

I'm using MySQL, and I have created 3 tables: 我正在使用MySQL,并创建了3个表:

CREATE TABLE user (
    id integer NOT NULL AUTO_INCREMENT, 
    name varchar(255), 
    PRIMARY KEY (id)
);

CREATE TABLE group (
    id integer NOT NULL AUTO_INCREMENT,
    name varchar(255),
    PRIMARY KEY (id)
);

CREATE TABLE group_user (
    user_id int NOT NULL,
    group_id int NOT NULL,
    PRIMARY KEY (user_id, group_id),
    KEY group_id (group_id),
    CONSTRAINT group_user_ibfk_1
    FOREIGN KEY (user_id) REFERENCES user (id),
    CONSTRAINT group_user_ibfk_2
    FOREIGN KEY (group_id) REFERENCES group (id)
);

I managed to link an user to a group by creating this new User, passing to its constructor a group, and calling my userDao.save() method: 我设法通过创建此新用户,将其传递给其构造函数一个组并调用我的userDao.save()方法来将用户链接到组:

userDao.save(new User(name, groups));

Now I want to edit my created user and make him belong to another group. 现在,我要编辑创建的用户并使他属于另一个组。 How can I do this without creating a new user? 如何在不创建新用户的情况下执行此操作?

For example, I have this user, who is in no group: 例如,我有这个用户,他不在任何组中:

INSERT INTO user VALUES(1, 'Jordan');

And these groups: 这些小组:

INSERT INTO group VALUES(1, 'Group 1');
INSERT INTO group VALUES(2, 'Group 2');

Now, how can I (in Java), link my user to Group 1 and Group 2? 现在,如何(在Java中)将用户链接到组1和组2?

You have to select a group entity from the database with the id of your choice. 您必须从数据库中选择具有您选择的ID实体。 You either use the JPA interface for that entity with the method findById or create your own custom method in the interface. 您可以通过findById方法为该实体使用JPA 接口 ,或者在该接口中创建自己的自定义方法。

When you have the entity for the group , you add it on to the User entity field groups . 当拥有该的实体时,可以将其添加到“ 用户实体”字段组中 After that you save the user entity . 之后, 保存用户实体

The same process goes to the other side group in a bi-directional relationship. 相同过程以双向关系进入另一侧

Recommended reading: 推荐阅读:

  1. Difference between unidirectional and bidirectional associations 单向和双向关联之间的区别
  2. A bidirectional association has two sides - owner side and an inverse side 双向关联具有两个方面-所有者方面和反方面
  3. Hibernate ManyToMany persistance tutorial Hibernate ManyToMany持久性教程

Create table like as: 创建表,如下所示:

mysql> CREATE TABLE users (
    ->     id integer NOT NULL AUTO_INCREMENT, 
    ->     name varchar(255), 
    ->     PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.24 sec)

mysql> CREATE TABLE groups (
    ->     id integer NOT NULL AUTO_INCREMENT,
    ->     name varchar(255),
    ->     PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.17 sec)

mysql> CREATE TABLE group_users (
    ->     user_id int NOT NULL,
    ->     group_id int NOT NULL,
    ->     PRIMARY KEY (user_id, group_id),
    ->     CONSTRAINT group_user_ibfk_1
    ->     FOREIGN KEY (user_id) REFERENCES users(id),
    ->     CONSTRAINT group_user_ibfk_2
    ->     FOREIGN KEY (group_id) REFERENCES groups(id)
    -> );
Query OK, 0 rows affected (0.23 sec)

Inserting dummy data into it: 向其中插入伪数据:

mysql> INSERT INTO user VALUES(1, 'Jordan');
Query OK, 1 row affected (0.09 sec)

mysql> INSERT INTO users VALUES(1, 'Jordan');
Query OK, 1 row affected (0.08 sec)

mysql> 
mysql> INSERT INTO groups VALUES(1, 'Group 1');
Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO groups VALUES(2, 'Group 2');
Query OK, 1 row affected (0.02 sec)

mysql> insert into group_users values(1,1);
Query OK, 1 row affected (0.05 sec)

mysql> insert into group_users values(1,2);
Query OK, 1 row affected (0.08 sec)

Actual Data in tables look like: 表中的实际数据如下所示:

mysql> select * from users;
+----+--------+
| id | name   |
+----+--------+
|  1 | Jordan |
+----+--------+
1 row in set (0.00 sec)

mysql> select * from groups;
+----+---------+
| id | name    |
+----+---------+
|  1 | Group 1 |
|  2 | Group 2 |
+----+---------+
2 rows in set (0.00 sec)

mysql> select * from group_users;
+---------+----------+
| user_id | group_id |
+---------+----------+
|       1 |        1 |
|       1 |        2 |
+---------+----------+
2 rows in set (0.00 sec)

Data after joined the all of the tables will look like. 加入所有表后的数据将如下所示。

mysql> select u.id user_id, u.name user_name,g.id group_id, g.name group_name from users u, groups g, group_users gu where u.id = gu.user_id and g.id = gu.group_id;
+---------+-----------+----------+------------+
| user_id | user_name | group_id | group_name |
+---------+-----------+----------+------------+
|       1 | Jordan    |        1 | Group 1    |
|       1 | Jordan    |        2 | Group 2    |
+---------+-----------+----------+------------+
2 rows in set (0.05 sec)

Hope, you cleared with the design, and how it will work in your case. 希望您已清除设计,以及如何在您的情况下使用。

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

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