我有一个B类,其中有一个包含A类对象的集合。 A类的对象可以相互引用。 因此,我正在从类B加载对象,该对象已经添加了类A的一个对象。现在,我从类A添加一个新对象,第一个将引用该对象。当我尝试保存此内容时,大多数情况下它将以EntityNotFoundException结尾。我可以尝试从最后一项保存到第一项,但是如果您看到以下示例,则此方法将无效:
public class A implements java.io.Serializable {
private BigInteger id;
private A succes;
private A fail;
public A(BigInteger id) {
this.id = id;
}
public void setSuccess(A a) {
this.success = a;
}
public void setFail(A a) {
this.fail = a;
}
}
public class B implements java.io.Serializable {
private Set<A> setA = new HashSet<A>();
public void addA(A a) {
this.setA.add(a);
}
public Set<A> getSetA() {
return this.setA;
}
}
public class Util {
public static void update(B b) throws JDBCException, PSQLException {
EntityManager em = null;
EntityTransaction tx = null;
try {
em = HibernateUtil.getEntityManagerFactory().createEntityManager();
tx = em.getTransaction();
tx.begin();
em.merge(b);
tx.commit();
} catch (Exception e) {
tx.rollback();
logger.error(e);
e.printStackTrace();
Throwable cause = e.getCause();
if (cause instanceof JDBCException) {
throw (JDBCException) cause;
}
if (cause instanceof PSQLException) {
throw (PSQLException) cause;
}
} finally {
em.close();
}
}
public static BigInteger getNextID() {
// returns next value of sequence
}
}
public static void main(String[] args) {
B b = ... // load from DB
A a1 = b.getSetA.get(0);
A a2 = new A(Util.getNextID());
A a3 = new A(Util.getNextID());
A a4 = new A(Util.getNextID());
a1.setSuccess(a2);
a2.setSuccess(a3);
a3.setSuccess(a4);
a4.setFail(a2);
b.addA(a2);
b.addA(a3);
b.addA(a4);
Util.update(b); // throws javax.persistence.EntityNotFoundException Unable to find A with id xxx
}
来自B类的XML-HBM文件:
<set embed-xml="true" fetch="select" cascade="all-delete-orphan"
lazy="true" mutable="true" name="A"
optimistic-lock="true" table="A" inverse="true"
sort="unsorted">
<key>
<column name="A_ID" />
</key>
<one-to-many
class="A" embed-xml="true"
not-found="exception" />
</set>
我该如何解决?
编辑: 我可以使用
em.unwrap(Session.class).update("B", b);
但这以IllegalArgumentException结尾:当从类A中删除对象时,删除分离的实例。