[英]JPA, Spring nested transactions
I have to persist an object O that contains a list of OL objects in one transaction: 我必须在一个事务中持久保存包含OL对象列表的对象O:
@Entity
public class O {
@OneToMany
private List<OL> olist;
// getters/setters
}
I'm reading O and OL from a file (xml interface) and have to insert them into the DB. 我正在从文件(xml接口)读取O和OL,并且必须将它们插入数据库。 The condition is the following: if an exception is thrown while persisting an OL object, ignore and continue with other OLs:
条件如下:如果在保留OL对象时引发异常,请忽略并继续使用其他OL:
@Transactional
private persistO(...) {
O o = new O();
o.set(...);
oDao.persist(o);
for (int i = 0; i < olCount; i++) {
OL ol = new OL();
ol.set(...);
try {
olDao.persist(ol);
em.flush();
}
catch(ConstraintViolationException ex) {
logger.warn()...;
}
}
}`
The problem is that at the first ConstraintViolationException
the transaction is set to rollbackOnly and nothing gets persisted. 问题在于,在第一个
ConstraintViolationException
事务被设置为rollbackOnly并且没有任何持久化。
org.springframework.transaction.TransactionSystemException:
Could not commit JPA transaction;
nested exception is javax.persistence.RollbackException:
Transaction marked as rollbackOnly
Question: How can this be achieved with JPA (Hibernate + Spring)? 问题:如何使用JPA(Hibernate + Spring)来实现?
Note 注意
@Transactional(propagation = Propagation.PROPAGATION_REQUIRES_NEW)
cannot be used. @Transactional(propagation = Propagation.PROPAGATION_REQUIRES_NEW)
。 What you are describing sounds a bit self-contradictory, in terms of transactions. 就交易而言,您所描述的内容听起来有些矛盾。 Transactions are meant to be all or nothing.
交易意味着全部或全部。 Why would an OL add fail?
为什么OL添加失败?
Reading between the lines, you are trying to do an add with no overwrite. 在两行之间读取时,您尝试做一个没有覆盖的添加。 That sounds a bit suspicious, from a design standpoint.
从设计的角度来看,这听起来有点可疑。 How would there be existing OL without an existing O?
没有现有的O怎么会有现有的OL? You could using SQL to blindly delete any orphan OL, if that's what's going on.
如果发生这种情况,您可以使用SQL盲目删除任何孤立的OL。 This also raises the question whether you.
这也引发了一个问题。 using surrogate keys.
使用代理键。
You could add the new O and persist, before adding any OL instances. 您可以添加新的O并保留,然后再添加任何OL实例。 You could then flush and retrieve the O, which would retrieve any existing OL.
然后,您可以刷新并检索O,这将检索任何现有的OL。 You would then add your new OL and persist.
然后,您将添加新的OL并保留。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.