I have the following relationship:
// In A.java class
@OneToMany(mappedBy="a", fetch=FetchType.LAZY)
@Cascade(CascadeType.SAVE_UPDATE)
private List<B> bList;
// In B.java class
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="id_a")
@Cascade(CascadeType.SAVE_UPDATE)
private A a;
I get this exception:
StaleStateException: Batch update returned unexpected row count from update
When I try to saveOrUpdate
entity a after deleting b from it.
// first delete old b record
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
a.getBList().remove(b);
b.setA(null);
session.delete(b);
// session.clear(); // this would solve my problem, but is it correct??
session.getTransaction().commit();
// then insert new b record
Session session=HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
B b=new B();
a.getBList().add(b);
b.setA(a);
session.saveOrUpdate(a);
session.getTransaction().commit(); // this throw exception
These two operation are not in the same method of course, are fired by gui event.
Is session.clear
the real solution? Am I (probably) doing wrong?
Removing session.delete(b)
solves the "problem"... so, what is the correct way?