Deletion, Spring Data and JPATransactionManager
Recently I have been adding Hibernate ORM to the HaikuDepotServer for a new feature. While doing this, I ran into a problem with Spring Data. Even using basic method on a concrete interface extending JPARepository
such as…
void delete(T entity);
…yields an exception NoTransactionException
. This was confusing because the service-level logic was wrapped in a Spring TransactionTemplate#execute
call which would ensure that it was in a transaction. The TransactionTemplate
instance is constructed with an instance of PlatformTranscationManager
which has various sub-classes two of which are;
JDBCTranscationManager
JPATransactionManager
By default, Spring will instantiate a JDBCTranscationManager
in the Spring context but this doesn’t work with JPA which is, in turn, used by Spring Data. Unhelpfully the machinery in Spring Data doesn’t point this problem out and will simply claim there’s no transaction in progress and/or simply not execute the delete(..)
invocation.
The way out of this is to explicitly setup a JPATransactionManager
in the Spring configuration logic;
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}