【发布时间】:2013-04-21 19:13:37
【问题描述】:
我有一个 JPA 实体类 User,其用户名为 @ID,但没有父实体组。我需要确保当两个并行事务尝试持久化具有相同用户名的新用户时,只有一个被提交,另一个被回滚。
例子:
User bob = new User("bob");
EntityTransaction transaction = em.getTransaction();
try {
transaction.begin();
User u = em.find(User.class, bob.id());
if (u == null) {
em.persist(bob);
} else {
// identical user already existed before the transaction
throw new UserExistsException();
}
transaction.commit();
} catch (RollbackException e) {
// identical user was created during the transaction
throw new UserExistsException();
}
根据 Datastore 文档,事务遵循乐观锁定方法:
“当事务开始时,App Engine 通过检查事务中使用的实体组的最后更新时间来使用乐观并发控制。在为实体组提交事务时,App Engine 再次检查实体的最后更新时间“ (https://developers.google.com/appengine/docs/java/datastore/transactions)
在持久化事务之前不存在的新(根)实体时,这是否有效?就我而言,App Engine 是否会检查另一个事务是否同时保留了具有相同 ID 的用户?如果是这样,我是否需要一个显式的 @Version 字段来实现这个目的?
【问题讨论】:
-
我刚刚遇到this discussion post,它声称在这种情况下低级 API 会抛出 ConcurrentModificationException。任何人都可以确认,理想情况下也适用于 JPA/JDO?
-
我在发布此stackoverflow.com/questions/27370112/… 后发现了您的问题,您自己解决了吗?
标签: java google-app-engine datanucleus