org.springframework.dao.DataIntegrityViolationException:具有相同标识符值的另一个对象已与会话关联 Hibernate 5将临时对象的ID保存在数据库中以用作子级父关系后,不会填充该ID。 我正在遵循班级等级制度:
public class A{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
....
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "parent")
private List<B> listB;
....
private C c;
}
public class B{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
....
@ManyToOne
@JoinColumn(name = "parent_id")
private A parent;
....
}
public class C{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
....
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "parent")
private List<D> listD;
....
}
public class D{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
....
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private C parent;
....
}
public interface ADao extends JpaRepository<A, Long>, JpaSpecificationExecutor<A> {}
@Autowired
ADao aDao;
A a = new A();
B b1 = new B();
B b2 = new B();
b1.setParent(a);
b2.setParent(a);
C c = new C();
D d1 = new D();
D d2 = new D();
d1.setParent(c);
d2.setParent(c);
List<B> blist = new ArrayList<B>();
blist.add(b1);
blist.add(b2);
a.setListB(blist);
List<D> dlist = new ArrayList<D`>();
dlist.add(d1);
dlist.add(d2);
c.setListD(dlist);
aDao.save(a);
当我尝试保存如下对象时:
我收到以下异常
org.springframework.dao.DataIntegrityViolationException: A different object with the same identifier value was already associated with the session : [D#0]; nested exception is javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [D#0]
Hibernate5似乎没有为孩子填充父母的ID,就像在调试期间,即使在保存操作之后,我的a.getId和c.getId都为0。
到目前为止,我已经尝试设置
hibernate.id.new_generator_mappings=false
session.flush()
session.merge()
session.refresh()