私はstackoverflowの投稿を検索しましたが、これが重複していないことを願っています。
初めてオプティミスティックロックを試してみました。スプリングマネージド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
2番目のアプローチ:トランザクションの管理
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
3番目のアプローチ:共有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
前もって感謝します!