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

前端 未结 4 1194
我在风中等你
我在风中等你 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:15

    Spring Data JPA automatically runs CRUD method in transactions for you (without needing to set up anything except a transaction manager). If you want to use transactions for your query methods, you can simply add @Transactional to these:

    interface MyRepository extends CrudRepository {
    
      @Transactional
      @Modifying
      @Query(value = "TRUNCATE TABLE MyTable", nativeQuery = true)
      void clear();
    }
    

    On a more general note, what you have declared here is logically equivalent to CrudRepository.deleteAll(), except that it (your declaration) doesn't honor JPA-level cascades. So I wondered that's really what you intended to do. If you're using Spring Boot, the activation and transaction manager setup should be taken care of for you.

    If you want to use @Transactional on the service level, you need to setup both a JpaTransactionManager and activate annotation based transaction management through either or @EnableTransactionManagement (looks like the activation was the missing piece on your attempt to create transactions on the service layer).

提交回复
热议问题