JoinTable 双向关联后保存,关联表重复保存

来源:互联网 发布:vivo深圳研发待遇知乎 编辑:程序博客网 时间:2024/06/06 11:04
双向table时:
如果双向关联后保存,会重复插入。
如果单向关联,就没问题。
或者,使用单向JoinTable,双向关联也不会重复插入。
@OneToMany(cascade = {CascadeType.ALL},fetch = FetchType.LAZY)@JoinTable(name="m_o_s",joinColumns = {@JoinColumn(name = "m")},inverseJoinColumns = {@JoinColumn(name="s")})
@ManyToOne( fetch = FetchType.LAZY)@JoinTable(name="m_o_s",joinColumns = {@JoinColumn(name = "s")},inverseJoinColumns = {@JoinColumn(name="m")})
单向保存,更新时:
OrgEntity orgEntity = new OrgEntity();orgEntity.setId(UUID.randomUUID().toString());Set<SpaceEntity> set = new HashSet<>();SpaceEntity spaceEntity = getSpaceEntity();spaceEntity.setOrg(orgEntity);set.add(spaceEntity);orgEntity.setSpaces(set);
Hibernate: insert into test.org (name, id) values (?, ?)
Hibernate: insert into test.space (name, id) values (?, ?)
Hibernate: insert into m_o_s (m, s) values (?, ?)
双向保存:
OrgEntity orgEntity = new OrgEntity();orgEntity.setId(UUID.randomUUID().toString());Set<SpaceEntity> set = new HashSet<>();SpaceEntity spaceEntity = getSpaceEntity();spaceEntity.setOrg(orgEntity);set.add(spaceEntity);orgEntity.setSpaces(set);
Hibernate: insert into test.org (name, id) values (?, ?)
Hibernate: insert into test.space (name, id) values (?, ?)
Hibernate: insert into m_o_s (m, s) values (?, ?)
Hibernate: insert into m_o_s (m, s) values (?, ?)
0 0
原创粉丝点击