我有一个问题,就是在持久化实体时,正在删除另一个实体中的集合。
我有一个实体(“容器”)(身份1),在其内部集合中持有一个“内部”。
当我来坚持另一个容器(id 3),再次使用另一个内部的Inners of Collection时,第一个实体的Inner将被删除。
我想不出这个的原因。我的班级注释或任何其他解释是否有问题?
“容器”类:
@Entity
@Table(name = "container")
public class Container
{
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_seq")
private Integer id;
@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
@LazyCollection(LazyCollectionOption.TRUE)
@JoinTable(name = "container_inner", joinColumns = {@JoinColumn(name = "container_id", nullable = false, updatable = false)}, inverseJoinColumns = {@JoinColumn(name = "inner_id", nullable = false, updatable = false)})
private Set<Inner> inners = new HashSet<>();
}
“内在”类:
@Entity
@Table(name = "INNER")
public class Inner
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Integer id = HelperUtils.defaultId;
@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, mappedBy = "inners")
@LazyCollection(LazyCollectionOption.FALSE)
private Set<Container> containers = new HashSet<>();
}
坚持代码:
em.persist(container);
em.flush();
JPA输出:
Hibernate: insert into container [...]
Hibernate: delete from container_inner where container_id=?
H2输出:
/*SQL #:1*/call next value for id_seq;
/*SQL l:539 #:1*/insert into container (ID) values {1: 3};
/*SQL */SELECT SCOPE_IDENTITY() WHERE SCOPE_IDENTITY() IS NOT NULL;
/*SQL l:84 #:1*/delete from container_inner where container_id=? {1: 1};
/*SQL */SELECT SCOPE_IDENTITY() WHERE SCOPE_IDENTITY() IS NOT NULL;