Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT

后端 未结 3 1615
闹比i
闹比i 2020-12-29 01:55

This post is in continuation of JPA How to get the value from database after persist

When I execute the following I am getting following exception, how can I resolve

3条回答
  •  -上瘾入骨i
    2020-12-29 02:20

    Injecting EntityManagerFactory instead of EntityManager and javax.transaction.Transactional annotation on method solved my issue as shown below.

    //Autowire EntityManagerFactory
    @PersistenceUnit(unitName = "readwrite.config")
    private EntityManagerFactory entityManagerFactory;
    
    
    //Use below code on create/update
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    
    entityManager.getTransaction().begin();
    if (!ObjectUtils.isEmpty(entity) && !entityManager.contains(entity)) {
       entityManager.persist(entity);
       entityManager.flush();
    }
    entityManager.getTransaction().commit();
    

提交回复
热议问题