I am having problems with transactions using the Hibernate implementation of JPA (I follow the Camel Example>
I am using the Hibernate JPA implementation:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.5.Final</version>
</dependency>
If I include the persistence.xml file in the META-INF folder, everything works fine:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="1.0">
<persistence-unit name="tracer" transaction-type="RESOURCE_LOCAL">
<class>org.apache.camel.processor.interceptor.jpa.JpaTraceEventMessage</class>
<properties>
<property name="hibernate.dialect" value="..."/>
<property name="hibernate.connection.driver_class" value="..."/>
<property name="hibernate.connection.url" value="..."/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.connection.username" value="..." />
<property name="hibernate.connection.password" value="..."/>
</properties>
</persistence-unit>
</persistence>
I want to use the Java method, so I delete persistence.xml and create the following beans:
@Configuration
@EnableTransactionManagement
public class AppConfiguration
{
@Bean public EntityManagerFactory entMngFac()
{
EntityManagerFactory emf = Persistence.createEntityManagerFactory("tracer");
return emf;
}
@Bean public DataSource ds()
{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("...");
dataSource.setUrl("...");
dataSource.setUsername( "..." );
dataSource.setPassword( "..." );
return dataSource;
}
@Bean public PlatformTransactionManager ptm(EntityManagerFactory emf, DataSource ds)
{
JpaTransactionManager jpat = new JpaTransactionManager();
jpat.setDataSource(ds);
jpat.setEntityManagerFactory(emf);
return jpat;
}
@Bean public TransactionTemplate tranTemp(PlatformTransactionManager ptm)
{
TransactionTemplate tt = new TransactionTemplate();
tt.setTransactionManager(ptm);
return tt;
}
}
After saving, when Camel tries to reset the created JPATracer object, I get the following exception:
javax.persistence.TransactionRequiredException: no transaction is in progress
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.checkTransactionNeeded(AbstractEntityManagerImpl.java:1171)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:1332)
at org.apache.camel.component.jpa.JpaProducer$1.doInTransaction(JpaProducer.java:86)
Which is a bit strange, since the error “no transaction” comes from the doInTransaction method.
My thoughts are that Camel starts a transaction and then Hibernate tries to clear the object and is not aware of the transaction Camel started? So there is some kind of mixture of transactions, but I can't figure out where.