为什么manyToMany连接表不插入

时间:2017-12-10 06:25:28

标签: spring-data-jpa

我使用所有默认的表名和列名,因此我没有添加连接表(实际上我尝试使用jointable)。双向,两个实体中只有一个具有mappedBy。

@Entity
public class User extends AbstractPersistable<Long> {

    @ManyToMany
    private Set<House> houses;


@Entity
public class House extends AbstractPersistable<Long> {

    @ManyToMany(mappedBy = "houses")
    Set<User> users;

应该很简单,除了在运行test之后hibernate没有插入jointable:

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoSmApplicationTests {

    @Test
    public void contextLoads() throws IOException {
        House p =new House();
        Set us = new HashSet<>();
        User u = userRepository.findOne(1L);
        us.add(u);
        p.setUsers(us);
        houseRepository.save(p);
    }

控制台只有一个&#34;插入&#34;:

Hibernate: select user0_.id as id1_5_0_, user0_.name as name2_5_0_ from user user0_ where user0_.id=?
Hibernate: insert into house (random) values (?)

1 个答案:

答案 0 :(得分:0)

当我们使用bidirectional关联时,我们必须提供&#39;帮助&#39;保持双方同步的方法,例如:

public House addUsers(User... users) {
  Stream.of(users).forEach(user -> {
    user.getHouses().add(this);
    this.users.add(user);
  });
  return this;
}

更多其他我们必须将cascade注释的@ManyToMany属性至少设置为MERGE,以告知Hibernate更新嵌套对象,当我们更新&#39;父&#39;实体:

@ManyToMany(mappedBy = "houses", cascade = CascadeType.MERGE)
private final Set<User> users = new HashSet<>();

然后我们可以得到正确的结果:

List<User> users = userRepo.save(Arrays.asList(
    new User("user1"),
    new User("user2"),
    new User("user3")
));

List<House> houses = houseRepo.save(Arrays.asList(
    new House("address1"),
    new House("address2")
));

houses.get(0).addUsers(users.get(0), users.get(1));
houses.get(1).addUsers(users.get(1), users.get(2));

houseRepo.save(houses);