【发布时间】:2012-09-21 17:39:50
【问题描述】:
我已经在 stackoverflow 中搜索了帖子,希望这不是重复的。
我是第一次尝试乐观锁定,我可以使用 spring 管理的 LockModeType 来实现,但无法自己定义 LockMode
以下是代码示例:
我正在使用以下方法注入持久性上下文:
@PersistenceContext
private EntityManager entityManager;
第一种方法:使用注释性事务
@Transactional
public void updateUserProfile(UserProfile userProfile) {
entityManager.lock(userProfile, LockModeType.OPTIMISTIC); // 1*
entityManager.merge(userProfile);
}
1 处的异常:java.lang.IllegalArgumentException: entity not in the persistence context
第二种方法:管理事务
public void updateUserProfile(UserProfile userProfile) {
entityManager.getTransaction().begin(); // 2*
entityManager.lock(userProfile, LockModeType.OPTIMISTIC);
entityManager.merge(userProfile);
entityManager.getTransaction().commit();
}
2 处的异常:Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
第三种方法:由于共享 entityManager 出现异常,我还尝试从 entityManagerFactory 创建 EntityManager。
@Transactional
public void updateUserProfile(UserProfile userProfile) {
EntityManager em = entityManager.getEntityManagerFactory().createEntityManager();
em.getTransaction().begin();
em.lock(userProfile, LockModeType.OPTIMISTIC); // 3*
em.merge(userProfile);
em.getTransaction().commit();
}
3 处的异常:entity not in the persistence context
在我的应用程序上下文中,我使用org.springframework.orm.jpa.JpaTransactionManager 定义transactionManager 和org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean 定义entityManagerFactory
提前致谢!
【问题讨论】:
-
你到底想达到什么目的?
-
我正在尝试通过定义 lockModeType 来实现乐观锁定。如果我不介绍这行 entityManager.lock(userProfile, LockModeType.OPTIMISTIC);在我的第一种方法中,一切都执行得很好并且版本增加了。但是它不提供覆盖spring默认的LockModeType的功能。希望有帮助。谢谢!
-
实体管理器工厂附加的持久单元中是否缺少实体?它应该在
META-INT/persistence.xml。 -
没有 Abhinav,持久性单元中没有缺少实体,我正在使用 entityManagerFactory 的 packagesToScan 属性为实体提供基础包。
标签: java spring jpa transactions