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

You should use TransactionTemplate object to manage transaction imperatively:

transactionTemplate.execute(
    status -> em.createNativeQuery("TRUNCATE TABLE MyTable).executeUpdate());

To create TransactionTemplate just use injected PlatformTransactionManager:

transactionTemplate = new TransactionTemplate(platformTransactionManager);

And if you want to use new transaction just invoke

transactionTemplate.setPropagationBehavior(
    TransactionDefinition.PROPAGATION_REQUIRES_NEW);

As a workaround I now created a new EntityManager explicit using the EMF, and starting the transaction manually.

@Autowired
private EntityManagerFactory emf;

public void clearTable() {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    em.createNativeQuery("TRUNCATE TABLE MyTable").executeUpdate();
    tx.commit();
    em.close();
}

That's probably not ideal, but works for the moment.


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<MyEntity, Integer> {

  @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 <tx:annotation-driven /> or @EnableTransactionManagement (looks like the activation was the missing piece on your attempt to create transactions on the service layer).