How to manually start a transaction on a shared EntityManager in Spring?

前端 未结 4 1188
我在风中等你
我在风中等你 2020-12-25 11:36

I have a LocalContainerEntityManagerFactoryBean as EntityManager instance.

To quickly drop a full tables\' content, I want to run the follo

4条回答
  •  眼角桃花
    2020-12-25 12:35

    @Transactional annotation should not be applied on Dao method but on a service method. Although your code says DatabaseService is a service, but by inserting EntityManger inside a service does not make any sense.

    Correct way to implement is to create a Dao like below.

    @Repository
    public class DatabaseDao {
        @PersistenceContext
        private EntityManager em;
    
        public void clear() {
            em.createNativeQuery("TRUNCATE TABLE MyTable").executeUpdate();
        }
    }
    

    Then call the dao method from a service method with @Transactional annotation.

    @Service
    public class DatabaseService {
        @Autowired
        private DatabaseDao dao;
    
        @Transactional
        public void clear() {
            dao.clear();
        }
    }
    

    Also, add @EnableTransactionManagement in your Configuration class

提交回复
热议问题