我有一个用例,父母的子女映射到同一个大孩子(已存在于数据库中)。当我坚持父母我得到
NonUniqueObjectException: A different object with the same identifier value .....
关系是:
A -> C
A -> B -> C
A->C is m:m
B->C is m:m
A->B is 1:1
当C对象对A和B都相同时会出现问题。
public class A {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Valid
@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST,CascadeType.MERGE})
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
@Fetch(FetchMode.SUBSELECT)
@JoinTable(name = "a_c",joinColumns = @JoinColumn(name="a_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name="c_id", referencedColumnName = "id"))
private Set<C> cs;
@Valid
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "b_id")
private B b;
}
public class B {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Valid
@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST,CascadeType.MERGE})
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
@Fetch(FetchMode.SUBSELECT)
@JoinTable(name = "b_c",joinColumns = @JoinColumn(name="b_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name="c_id", referencedColumnName = "id"))
private Set<C> cs;
}
public class C {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonIgnore
@Fetch(FetchMode.SELECT)
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "cs")
public Set<A> as;
@JsonIgnore
@Fetch(FetchMode.SELECT)
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "cs")
private Set<B> bs;
}
现在,如果我尝试使用具有相同主键A和B的C对象持久保存A,则会出现此异常。
一个hack是首先获取大孩子并设置子对象,但寻找其他选项。