How to start a transaction in JPA using entityManager

前端 未结 4 539
陌清茗
陌清茗 2021-01-02 13:26

I have started working on an application which uses spring, hibernate, JPA, SOAP webservices. Now there is a requirement that certain queries have to be run in a transaction

相关标签:
4条回答
  • 2021-01-02 13:36

    The EntityManager instance returned by @PersistenceContext is always a container managed EntityManager. And container managed EntityManager are always JTA EntityManagers and hence their lifecycle is managed by the container. I guess now it makes sense as to why it is illegal to call getTransaction() on them.This might help

    0 讨论(0)
  • 2021-01-02 13:38

    @Transactional annotation will do exactly what you need.

    http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html#transaction-declarative-annotations

    0 讨论(0)
  • 2021-01-02 13:39

    The add a hibernate.jta.allowTransactionAccess property with the value true and you should be allowed to use it manually. Though it's not a good practice to mix your strategies, having some code managed by JTA, some manually.

    0 讨论(0)
  • 2021-01-02 13:49

    Try injecting EntityManagerFactory and then creating the EntityManager manually:

    @PersistenceUnit
    private EntityManagerFactory entityManagerFactory;
    
    public boolean processBills() throws Exception{
    
       EntityManager em = entityManagerFactory.createEntityManager();
    
       EntityTransaction tx = null;
    
       Session session = null;
    
       try{
    
           session = em.unwrap(Session.class);
           tx = em.getTransaction();
    
    0 讨论(0)
提交回复
热议问题