No Persistence provider for EntityManager named cache - java

Message.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
#Entity
#Table(name="MESSAGES")
#Cache(region = "messages", usage = CacheConcurrencyStrategy.READ_WRITE)
public class Message {
Message(){
}
Message(String message){
message_text=message;
}
#Id #GeneratedValue
#Column(name="MESSAGE_ID")
public Long id;
#Column(name="MESSAGE_TEXT")
public String message_text;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMessage_text() {
return message_text;
}
public void setMessage_text(String message_text) {
this.message_text = message_text;
}
}
Ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" />
<cache name="messages" maxElementsInMemory="10" eternal="true" overflowToDisk="false" />
</ehcache>
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="annotation">
<properties>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:#ebiz-dev-db-esb:1521:esbd"/>
<property name="hibernate.connection.username" value="CUST_INFO"/>
<property name="hibernate.connection.password" value="POUND987"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle9Dialect"/>
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="3000"/>
<property name="show_sql" value="true"/>
<property name="format_sql" value="true"/>
<property name="hibernate.cache.region.factory_class" value="net.sf.ehcache.hibernate.EhCacheRegionFactory"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.EhCacheProvider" />
<property name="hibernate.cache.provider_configuration_file_resource_path" value="ehcache.xml" />
</properties>
</persistence-unit>
</persistence>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>HibernateWithAnnotation</groupId>
<artifactId>HibernateWithAnnotation</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>HibernateWithAnnotation</name>
<repositories>
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.6.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.5</version>
</dependency>
</dependencies>
</project>
TestAnnotation class
package com.annotation;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
public class TestAnnotation {
public static void main(String args[]){
EntityManagerFactory factory=Persistence.createEntityManagerFactory("annotation");
EntityManager manager=factory.createEntityManager();
EntityTransaction transaction=manager.getTransaction();
transaction.begin();
manager.persist(new Message("My Entity Test One More Example New"));
transaction.commit();
System.out.println("First time calling Message Object");
getMessage(manager,23);
System.out.println("Second time calling Message Object");
getMessage(manager,23);
factory.close();
}
public static void getMessage(EntityManager manager,long id){
EntityTransaction transaction1=manager.getTransaction();
transaction1.begin();
Query q=manager.createQuery("from Message m where m.id="+id);
Message m=(Message)q.getSingleResult();
System.out.println(m.getMessage_text());
transaction1.commit();
}
}
My problem is: When I run this code from TestAnnotation class via main method I get the following error:
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named annotation
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:32)
at com.annotation.TestAnnotation.main(TestAnnotation.java:10)

Your persistence-unit is incomplete. See the documentation.
Add <class>com.annotation.TestAnnotation</class> to your persistence-unit node in your persistence.xml file before the properties node.
You likely also need transaction-type="RESOURCE_LOCAL" on you persistence-unit node.
For example, my working version uses:
pom.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.5.4-Final</version>
<scope>runtime</scope>
</dependency>
persistenct.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="MyPU" transaction-type="RESOURCE_LOCAL">
<class>com.myentities.MyEntity</class>
<properties>
<property name="hibernate.cache.use_query_cache" value="false"/>
<property name="hibernate.cache.use_second_level_cache" value="false"/>
<!-- These lines can be used for debugging -->
<!--<property name="show_sql" value="true"/>-->
<!--<property name="format_sql" value="true"/>-->
</properties>
</persistence-unit>
</persistence>
My DAO class:
private EntityManager m_entityManagerFactory;
// initializer (this is costly, do only 1x on post construct)
m_entityManager = createEntityManagerFactory( jdbcDriverName, jdbcURL, dbUserName, dbPassword );
// when needed (less costly, can do 1x or whenever you need the entity manager)
EntityManager entityManager = m_entityManagerFactory.createEntityManager();
private EntityManagerFactory createEntityManagerFactory (
#NotNull final String jdbcDriverName,
#NotNull final String jdbcURL,
#NotNull final String dbUserName,
#NotNull final String dbPassword )
{
final Properties properties = new Properties();
properties.put( "hibernate.connection.driver_class", jdbcDriverName );
properties.put( "hibernate.connection.url", jdbcURL );
properties.put( "hibernate.connection.username", dbUserName );
properties.put( "hibernate.connection.password", dbPassword );
return Persistence.createEntityManagerFactory( "AlertProcessorPU", properties );
}

Related

Flyway configuration java.lang.ClassNotFoundException: org.flyway.core.Flyway

I'm trying to connect flyway to my project which is using Spring 3.0.7.RELEASE version.
I found some solution here how to do it: https://blog.trifork.com/2014/12/09/integrating-flywaydb-in-a-spring-framework-application/
so I've made 1:1 like in the tutorial:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<jpa:repositories base-package="main" entity-manager-factory-ref="entityManagerFactoryBean"/>
<context:component-scan base-package="main"/>
<context:annotation-config/>
<bean class="org.springframework.orm.hibernate4.HibernateExceptionTranslator"/>
<!-- Flyway configuration -->
<bean id="flyway" class="org.Flyway.core.Flyway" init-method="migrate">
<property name="baselineOnMigrate" value="true" />
<property name="locations" value="classpath:db/migration" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" depends-on="flyway">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="main"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">none</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
</props>
</property>
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/db"/>
<property name="username" value="FITNESSAPPLICATION_USER"/>
<property name="password" value="FITNESSAPPLICATION_PASS"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean"/>
</bean>
<tx:annotation-driven/>
<mvc:annotation-driven/>
</beans>
with
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>fitnessapplication</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>1.14.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.14.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.2-1003-jdbc4</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.1</version>
</dependency>
</dependencies>
but org.flyway.core.Flyway" is marked on red and getting:
14-Dec-2020 16:32:44.204 SEVERE [http-nio-8080-exec-3] org.apache.catalina.core.StandardWrapperValve.invoke Allocate exception for servlet [DispatcherServlet]
java.lang.ClassNotFoundException: org.flyway.core.Flyway
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1358)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1180)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:257)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408)
at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1282)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1253)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:432)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:283)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:400)
at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:275)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.detectPersistenceExceptionTranslators(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.<init>(PersistenceExceptionTranslationInterceptor.java:79)
at org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisor.<init>(PersistenceExceptionTranslationAdvisor.java:70)
at org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:102)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1441)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1410)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:518)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:710)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:410)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:467)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:483)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:358)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:325)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1144)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1091)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:763)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:544)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:616)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:831)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1634)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
What is wrong here?
It should be org.flyway.core.Flyway instead of org.Flyway.core.Flyway.
I used dependency as following (used in spring mvc/Boot without xml based configuration)
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>5.2.4</version>
</dependency>
Created a class FlywayPostDeploy as following
import java.sql.Connection;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.callback.FlywayCallback;
public class FlyWayPostDeploy implements FlywayCallback {
#Override
public void beforeClean(Connection connection) {
throw new UnsupportedOperationException("beforeClean");
}
#Override
public void afterClean(Connection connection) {
throw new UnsupportedOperationException("afterClean");
}
#Override
public void beforeMigrate(Connection connection) {
throw new UnsupportedOperationException("beforeMigrate");
}
#Override
public void afterMigrate(Connection connection) {
throw new UnsupportedOperationException("afterMigrate");
}
#Override
public void beforeUndo(Connection connection) {
throw new UnsupportedOperationException("beforeUndo");
}
#Override
public void beforeEachUndo(Connection connection, MigrationInfo info) {
throw new UnsupportedOperationException("beforeEachUndo");
}
#Override
public void afterEachUndo(Connection connection, MigrationInfo info) {
throw new UnsupportedOperationException("afterEachUndo");
}
#Override
public void afterUndo(Connection connection) {
throw new UnsupportedOperationException("afterUndo");
}
#Override
public void beforeEachMigrate(Connection connection, MigrationInfo info) {
throw new UnsupportedOperationException("beforeEachMigrate");
}
#Override
public void afterEachMigrate(Connection connection, MigrationInfo info) {
throw new UnsupportedOperationException("afterEachMigrate");
}
#Override
public void beforeValidate(Connection connection) {
throw new UnsupportedOperationException("beforeValidate");
}
#Override
public void afterValidate(Connection connection) {
throw new UnsupportedOperationException("afterValidate");
}
#Override
public void beforeBaseline(Connection connection) {
throw new UnsupportedOperationException("beforeBaseline");
}
#Override
public void afterBaseline(Connection connection) {
throw new UnsupportedOperationException("afterBaseline");
}
#Override
public void beforeRepair(Connection connection) {
throw new UnsupportedOperationException("beforeRepair");
}
#Override
public void afterRepair(Connection connection) {
throw new UnsupportedOperationException("afterRepair");
}
#Override
public void beforeInfo(Connection connection) {
throw new UnsupportedOperationException("beforeInfo");
}
#Override
public void afterInfo(Connection connection) {
throw new UnsupportedOperationException("afterInfo");
}
}
And passed Datasource from bean class like this
public void setFlyWay(DriverManagerDataSource dataSource) {
try {
final Flyway flyway = new Flyway();
flyway.setDataSource(dataSource);
flyway.setBaselineOnMigrate(true);
final MigrationInfo migrationInfo = flyway.info().current();
LOGGER.info(migrationInfo);
flyway.repair();
flyway.migrate();
} catch (final Exception e) {
LOGGER.error("Flayway Exception : " + e);
}
}
and in resource folder as following with sql as intend refer

Is it possible to deploy multiple bundles to ServiceMix that use Hibernate Envers?

We are attempting to deploy multiple bundles in ServiceMix 6.1.4 that each make updates to a database and we want those updates to be audited with Hibernate Envers 4.3.6.FINAL. We are in the proof-of-concept stage, so we are only building the jar files and putting them into the deploy directory of the apache-servicemix-6.1.4 directory, with a separate datasource blueprint file for each.
Individually, the bundles work and audit just fine. But if you have both bundles deployed, one will fail with the error:
2018-04-20 14:00:10,635 | WARN | mix-6.1.4/deploy | container | 260 - org.apache.aries.jpa.container - 1.0.2 | Error creating EntityManagerFactory
org.hibernate.event.service.spi.EventListenerRegistrationException: Duplicate event listener found
at org.hibernate.event.service.internal.EventListenerGroupImpl.listenerShouldGetAdded(EventListenerGroupImpl.java:143)[252:org.hibernate.core:4.3.6.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.appendListener(EventListenerGroupImpl.java:108)[252:org.hibernate.core:4.3.6.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.appendListeners(EventListenerGroupImpl.java:102)[252:org.hibernate.core:4.3.6.Final]
at org.hibernate.event.service.internal.EventListenerRegistryImpl.appendListeners(EventListenerRegistryImpl.java:172)[252:org.hibernate.core:4.3.6.Final]
at org.hibernate.envers.event.spi.EnversIntegrator.integrate(EnversIntegrator.java:84)[254:org.hibernate.envers:4.3.6.Final]
at Proxy7c321f84_ab1f_4b15_a78a_66080ada210e.integrate(Unknown Source)[:]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:312)[252:org.hibernate.core:4.3.6.Final]
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1857)[252:org.hibernate.core:4.3.6.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)[251:org.hibernate.entitymanager:4.3.6.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)[251:org.hibernate.entitymanager:4.3.6.Final]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)[252:org.hibernate.core:4.3.6.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)[251:org.hibernate.entitymanager:4.3.6.Final]
at org.hibernate.osgi.OsgiPersistenceProvider.createContainerEntityManagerFactory(OsgiPersistenceProvider.java:112)[253:org.hibernate.osgi:4.3.6.Final]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.createEntityManagerFactories(EntityManagerFactoryManager.java:336)[260:org.apache.aries.jpa.container:1.0.2]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.registerEntityManagerFactories(EntityManagerFactoryManager.java:239)[260:org.apache.aries.jpa.container:1.0.2]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.bundleStateChange(EntityManagerFactoryManager.java:182)[260:org.apache.aries.jpa.container:1.0.2]
at org.apache.aries.jpa.container.impl.PersistenceBundleManager.modifiedBundle(PersistenceBundleManager.java:301)[260:org.apache.aries.jpa.container:1.0.2]
at org.apache.aries.util.tracker.hook.BundleHookBundleTracker$Tracked.customizerModified(BundleHookBundleTracker.java:500)[9:org.apache.aries.util:1.1.1]
at org.apache.aries.util.tracker.hook.BundleHookBundleTracker$Tracked.customizerModified(BundleHookBundleTracker.java:433)[9:org.apache.aries.util:1.1.1]
at org.apache.aries.util.tracker.hook.BundleHookBundleTracker$AbstractTracked.track(BundleHookBundleTracker.java:725)[9:org.apache.aries.util:1.1.1]
at org.apache.aries.util.tracker.hook.BundleHookBundleTracker$Tracked.bundleChanged(BundleHookBundleTracker.java:463)[9:org.apache.aries.util:1.1.1]
at org.apache.aries.util.tracker.hook.BundleHookBundleTracker$BundleEventHook.event(BundleHookBundleTracker.java:422)[9:org.apache.aries.util:1.1.1]
at org.apache.felix.framework.util.SecureAction.invokeBundleEventHook(SecureAction.java:1103)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.util.EventDispatcher.createWhitelistFromHooks(EventDispatcher.java:695)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.util.EventDispatcher.fireBundleEvent(EventDispatcher.java:483)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.Felix.fireBundleEvent(Felix.java:4403)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.Felix.startBundle(Felix.java:2092)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:955)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.startBundle(DirectoryWatcher.java:1243)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.startBundles(DirectoryWatcher.java:1215)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.doProcess(DirectoryWatcher.java:506)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.process(DirectoryWatcher.java:355)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.run(DirectoryWatcher.java:307)[7:org.apache.felix.fileinstall:3.5.2]
I created two simple bundles that can reproduce the issue based on the standard managed-jpa example code.
First pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.hibernate.osgi</groupId>
<artifactId>managed-jpa-test1</artifactId>
<version>1.0.0</version>
<packaging>bundle</packaging>
<dependencies>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.enterprise</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.karaf.shell</groupId>
<artifactId>org.apache.karaf.shell.console</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>4.3.6.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>3.0.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>org.hibernate.osgi.managed-jpa-test1</Bundle-SymbolicName>
<Bundle-Name>managed-jpa-test1</Bundle-Name>
<Bundle-Version>1.0.0</Bundle-Version>
<Private-Package>
org.hibernate.osgitest,
org.hibernate.osgitest.entity
</Private-Package>
<Import-Package>
org.hibernate.jpa,
org.apache.felix.service.command,
org.apache.felix.gogo.commands,
org.apache.karaf.shell.console;resolution:=optional;version="[3.0,4)",
org.apache.karaf.shell.commands;resolution:=optional;version="[3.0,4)",
javax.persistence;version="[1.0.0,2.1.0]",
<!-- Needed for proxying's Javassist enhancement during runtime -->
org.hibernate.proxy,
javassist.util.proxy,
*
</Import-Package>
<Meta-Persistence>META-INF/persistence.xml</Meta-Persistence>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>
Second pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.hibernate.osgi</groupId>
<artifactId>managed-jpa-test2</artifactId>
<version>1.0.0</version>
<packaging>bundle</packaging>
<dependencies>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.enterprise</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.karaf.shell</groupId>
<artifactId>org.apache.karaf.shell.console</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>4.3.6.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>3.0.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>org.hibernate.osgi.managed-jpa-test2</Bundle-SymbolicName>
<Bundle-Name>managed-jpa-test2</Bundle-Name>
<Bundle-Version>1.0.0</Bundle-Version>
<Private-Package>
org.hibernate.osgitest2,
org.hibernate.osgitest2.entity
</Private-Package>
<Import-Package>
org.hibernate.jpa,
org.apache.felix.service.command,
org.apache.felix.gogo.commands,
org.apache.karaf.shell.console;resolution:=optional;version="[3.0,4)",
org.apache.karaf.shell.commands;resolution:=optional;version="[3.0,4)",
javax.persistence;version="[1.0.0,2.1.0]",
<!-- Needed for proxying's Javassist enhancement during runtime -->
org.hibernate.proxy,
javassist.util.proxy,
*
</Import-Package>
<Meta-Persistence>META-INF/persistence.xml</Meta-Persistence>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>
First blueprint.xml:
<blueprint default-activation="eager"
xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://aries.apache.org/xmlns/jpa/v1.0.0"
xmlns:tx="http://aries.apache.org/xmlns/transactions/v1.0.0">
<bean id="dpService" class="org.hibernate.osgitest.DataPointServiceImpl">
<jpa:context unitname="managed-jpa-test1" property="entityManager"/>
<tx:transaction method="*" value="Required"/>
</bean>
<service ref="dpService" interface="org.hibernate.osgitest.DataPointService"/>
<bean id="integrator" class="org.hibernate.envers.event.spi.EnversIntegrator" />
<service ref="integrator" interface="org.hibernate.integrator.spi.Integrator" />
<command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">
<command>
<action class="org.hibernate.osgitest.command.AddCommand">
<property name="dpService" ref="dpService"/>
</action>
</command>
</command-bundle>
</blueprint>
Second blueprint.xml:
<blueprint default-activation="eager"
xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://aries.apache.org/xmlns/jpa/v1.0.0"
xmlns:tx="http://aries.apache.org/xmlns/transactions/v1.0.0">
<bean id="dpService2" class="org.hibernate.osgitest2.DataPointService2Impl">
<jpa:context unitname="managed-jpa-test2" property="entityManager2"/>
<tx:transaction method="*" value="Required"/>
</bean>
<service ref="dpService2" interface="org.hibernate.osgitest2.DataPointService2"/>
<bean id="integrator" class="org.hibernate.envers.event.spi.EnversIntegrator" />
<service ref="integrator" interface="org.hibernate.integrator.spi.Integrator" />
<command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">
<command>
<action class="org.hibernate.osgitest2.command.AddCommand2">
<property name="dpService2" ref="dpService2"/>
</action>
</command>
</command-bundle>
</blueprint>
DataPoint.java:
#Entity
#Audited
public class DataPoint {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
DataPoint2.java:
#Entity
#Audited
public class DataPoint2 {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
First persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="1.0">
<persistence-unit name="managed-jpa-test1" transaction-type="JTA">
<jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=test1/mssql)</jta-data-source>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
<property name="hibernate.archive.autodetection" value="class"/>
</properties>
</persistence-unit>
</persistence>
Second persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="1.0">
<persistence-unit name="managed-jpa-test2" transaction-type="JTA">
<jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=test2/mssql)</jta-data-source>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
<property name="hibernate.archive.autodetection" value="class"/>
</properties>
</persistence-unit>
</persistence>
DataPointService.java:
public interface DataPointService {
public void add(DataPoint dp);
}
DataPointServiceImpl.java:
public class DataPointServiceImpl implements DataPointService {
private EntityManager entityManager;
public void add(DataPoint dp) {
entityManager.persist( dp );
entityManager.flush();
}
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
}
AddCommand.java:
#Command(scope = "dp1", name = "add")
public class AddCommand implements Action {
#Argument(index=0, name="Name", required=true, description="Name", multiValued=false)
String name;
private DataPointService dpService;
public void setDpService(DataPointService dpService) {
this.dpService = dpService;
}
public Object execute(CommandSession session) throws Exception {
DataPoint dp = new DataPoint();
dp.setName( name );
dpService.add( dp );
return null;
}
}
DataPointService2.java:
public interface DataPointService2 {
public void add(DataPoint2 dp);
}
DataPointService2Impl.java:
public class DataPointService2Impl implements DataPointService2 {
private EntityManager entityManager2;
public void add(DataPoint2 dp) {
entityManager2.persist( dp );
entityManager2.flush();
}
public EntityManager getEntityManager2() {
return entityManager2;
}
public void setEntityManager2(EntityManager entityManager2) {
this.entityManager2 = entityManager2;
}
}
AddCommand2.java:
#Command(scope = "dp2", name = "add")
public class AddCommand2 implements Action {
#Argument(index=0, name="Name", required=true, description="Name", multiValued=false)
String name;
private DataPointService2 dpService2;
public void setDpService2(DataPointService2 dpService2) {
this.dpService2 = dpService2;
}
public Object execute(CommandSession session) throws Exception {
DataPoint2 dp = new DataPoint2();
dp.setName( name );
dpService2.add( dp );
return null;
}
}
datasource-test1.xml:
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
<bean id="test1DataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver"/>
<property name="url" value="jdbc:jtds:sqlserver://localhost:1433;databaseName=XXXX;tds=8.0;lastupdatecount=true;uselobs=false"/>
<property name="username" value="sa"/>
<property name="password" value="XXXXX"/>
</bean>
<service interface="javax.sql.DataSource" ref="test1DataSource">
<service-properties>
<entry key="osgi.jndi.service.name" value="test1/mssql"/>
</service-properties>
</service>
</blueprint>
datasource-test2.xml
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
<bean id="test2DataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver"/>
<property name="url" value="jdbc:jtds:sqlserver://localhost:1433;databaseName=XXXX;tds=8.0;lastupdatecount=true;uselobs=false"/>
<property name="username" value="sa"/>
<property name="password" value="XXXXX"/>
</bean>
<service interface="javax.sql.DataSource" ref="test2DataSource">
<service-properties>
<entry key="osgi.jndi.service.name" value="test2/mssql"/>
</service-properties>
</service>
</blueprint>
I think that is all the relevant files. Probably more than I need, but better safe than sorry.
We want to be able to offer the bundles as separate solutions that a customer can use depending on their needs. Like one HL7 bundle and a WebService bundle and so forth.
If it is only possible to have one bundle using Envers, then we will have to develop an additional bundle that does the database updates, but it would be better if the bundles could be self-contained.
You are offering the envers extension using
<bean id="integrator" class="org.hibernate.envers.event.spi.EnversIntegrator" />
<service ref="integrator" interface="org.hibernate.integrator.spi.Integrator" />
As this is an OSGi service it will be picked up by all bundles. So the bundle that starts last will see both and complain. Try to put this in its own bundle to make sure it is only registered once.

Wildfly Swarm EntityManager is null

I have a microservice which is a scheduler. I get a timing job via REST json.
I followed some tutorials on how to add the persistence.xml but it doesn't seem to work. I don't get any failure messages but the NullpointerException from the EntityManager.
It doesn't create the tables etc. so i think there is a problem with adding the persistence.xml too?
There is no problem in connecting to the datasource. i tested it and it seems to work properly.
SchedulerMain:
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset;
import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.datasources.DatasourceArchive;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
public class SchedulerMain {
public static void main(String[] args) {
try {
Container container = new Container();
container.start();
container.deploy(Swarm.artifact("mysql:mysql-connector-java", "mysql"));
deployApp(container);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void deployApp(Container container) throws Exception {
JAXRSArchive app = ShrinkWrap.create(JAXRSArchive.class);
app.as(DatasourceArchive.class).dataSource("Scheduler", (ds) -> {
ds.connectionUrl("jdbc:mysql://localhost:3306/scheduler");
ds.driverName("mysql");
ds.userName("root");
ds.password("");
});
app.addAsWebInfResource(new ClassLoaderAsset("META-INF/persistence.xml", SchedulerMain.class.getClassLoader()),
"classes/META-INF/persistence.xml");
app.addAsLibrary(container.createDefaultDeployment());
app.addAllDependencies();
container.deploy(app);
}
}
ScheduleRESTResource:
#ApplicationScoped
#Path("/schedule")
public class ScheduleRESTResource {
#Inject
private SchedulerController schedulerController;
#Inject
private ScheduleBean scheduleBean;
#POST
#Path("/job")
#Consumes(MediaType.APPLICATION_JSON)
public void schedule(MySchedule schedule) throws IOException {
List<MySchedule> schedules = scheduleBean.getAllSchedules();
System.out.println(schedules.toString());
schedulerController.buildSchedule(schedule);
}
}
ScheduleBean:
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import de.fszm.scheduler.entities.MySchedule;
#Stateless
public class ScheduleBean {
#PersistenceContext(unitName = "Scheduler")
private EntityManager em;
public List<MySchedule> getAllSchedules() {
System.out.println("getAllSchedules");
List<MySchedule> schedules = new ArrayList<>();
if (em != null) {
schedules = em.createNamedQuery("Schedule.getAllSchedules", MySchedule.class).getResultList();
} else {
System.out.println("em is null");
}
return schedules;
}
}
persistence.xml:
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="Scheduler" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/Scheduler</jta-data-source>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/scheduler"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="drop-and-create"/>
</properties>
</persistence-unit>
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>...</groupId>
<artifactId>scheduler</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>scheduler</name>
<packaging>jar</packaging>
<properties>
<version.swarm>1.0.0.Beta6</version.swarm>
<version.mysql>5.1.6</version.mysql>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>bom</artifactId>
<version>${version.swarm}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>undertow</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>ejb</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>jaxrs-weld</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>datasources</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${version.mysql}</version>
</dependency>
<!-- <dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>wildfly-swarm-ejb</artifactId>
<version>1.0.0.Alpha5</version>
</dependency> -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.wildfly.swarm</groupId>
<artifactId>wildfly-swarm-plugin</artifactId>
<version>${version.swarm}</version>
<configuration>
</configuration>
<executions>
<execution>
<id>package</id>
<goals>
<goal>package</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>

Spring Hibernate MySQL - No connection?

I've a problem with connection to mysql. This is my code:
Dependencies:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Apache Database Connection Pool -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.10.Final</version>
</dependency>
<!-- MySQL JDBC Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
</dependencies>
Context:
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="com.packt.app" />
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/view/"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".html"/>
<property name="exposeSpringMacroHelpers" value="true"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://ADMIN-PC:3306/data"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="/WEB-INF/hibernate.cfg.xml" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="testDAO" class="com.packt.app.DAO.Impl.TestDAOImpl">
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
Controller:
#Controller
#RequestMapping("/tests")
public class TestController {
#Autowired
TestService testService;
#RequestMapping("/testslist.json")
public #ResponseBody List<Test> getTestList() {
return testService.getTests();
}
#RequestMapping("/layout")
public String getTestPartialPage(ModelMap modelMap) {
return "tests/layout";
}
}
Model:
#Entity
#Table(name = "test")
public class Test{
#Id
#GeneratedValue
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
///gettters and setters
}
Impl:
#Repository
public class TestDAOImpl implements TestDAO {
#Autowired
private SessionFactory sessionFactory;
public TestDAOImpl() {
}
public TestDAOImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
#Transactional
public List<Test> getTests() {
#SuppressWarnings("unchecked")
List<Test> tests = (List<Test>) sessionFactory.getCurrentSession()
.createCriteria(Test.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
return tests;
}
}
Angular Controller:
var TestsController = function($scope, $http) {
$scope.test = {};
$scope.editMode = false;
$scope.fetchTestList = function() {
$http.get('tests/testslist.json').success(function(testList){
$scope.tests = testList;
});
};
$scope.resetTestForm = function() {
$scope.resetError();
$scope.test = {};
$scope.editMode = false;
};
$scope.resetError = function() {
$scope.error = false;
$scope.errorMessage = '';
};
$scope.setError = function(message) {
$scope.error = true;
$scope.errorMessage = message;
};
$scope.fetchTestList()();
$scope.predicate = 'id';
};
Hibernate config:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="com.packt.app.model.Test"/>
</session-factory>
</hibernate-configuration>
Application runs without error, even when MySql Server off. In html view show me that list count "getTests" is 0. It looks like application not connection with MySQL Server. Whats wrong? Please help me.
The dialect in hibernate configuratiin is missing a L
Should be mysqlDialect i reckon.

Object is not saved in mysql schema by Hibernate 4 (Jpa 2.0 + Jta using Atomikos transaction manager)

I am reading the book Pro Spring 3 and in the chapter about Global Transactions there is some example code for persisting an object into two different mysql schemas.
I am running the code but the object is not saved in any of the two schemas.
Here is the code.
tx-jta-app-context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config />
<context:component-scan base-package="foo.bar.service.jta"/>
<bean id="dataSourceA" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">
<property name="uniqueResourceName">
<value>XADBMSA</value>
</property>
<property name="xaDataSourceClassName">
<value>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</value>
</property>
<property name="xaProperties">
<props>
<prop key="databaseName">prospring3_ch13a</prop>
<prop key="user">prospring3_ch13a</prop>
<prop key="password">prospring3_ch13a</prop>
</props>
</property>
<property name="poolSize">
<value>1</value>
</property>
</bean>
<bean id="dataSourceB" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">
<property name="uniqueResourceName">
<value>XADBMSB</value>
</property>
<property name="xaDataSourceClassName">
<value>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</value>
</property>
<property name="xaProperties">
<props>
<prop key="databaseName">prospring3_ch13b</prop>
<prop key="user">prospring3_ch13b</prop>
<prop key="password">prospring3_ch13b</prop>
</props>
</property>
<property name="poolSize">
<value>1</value>
</property>
</bean>
<!-- Construct Atomikos UserTransactionManager, needed to configure Spring -->
<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close">
<!-- when close is called, should we force transactions to terminate or not? -->
<property name="forceShutdown">
<value>true</value>
</property>
</bean>
<!-- Also use Atomikos UserTransactionImp, needed to configure Spring -->
<bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp">
<property name="transactionTimeout">
<value>300</value>
</property>
</bean>
<!-- Configure the Spring framework to use JTA transactions from Atomikos -->
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager">
<ref bean="atomikosTransactionManager"/>
</property>
<property name="userTransaction">
<ref bean="atomikosUserTransaction"/>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="emfBase" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" abstract="true">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="foo.bar.domain"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.transaction.factory_class">
${com.atomikos.icatch.jta.hibernate3.AtomikosJTATransactionFactory}
</prop>
<prop key="hibernate.transaction.manager_lookup_class">
${com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup}
</prop>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="emfA" parent="emfBase">
<property name="dataSource" ref="dataSourceA"/>
</bean>
<bean id="emfB" parent="emfBase">
<property name="dataSource" ref="dataSourceB"/>
</bean>
</beans>
foo/bar/service/jta/ContactServiceImpl.java :
package foo.bar.service.jta;
import foo.bar.domain.Contact;
import foo.bar.service.ContactService;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
#Service("contactService")
#Repository
#Transactional
public class ContactServiceImpl implements ContactService{
#PersistenceContext(unitName = "emfA")
private EntityManager emA;
#PersistenceContext(unitName = "emfB")
private EntityManager emB;
#Override
#Transactional(readOnly = true)
public List<Contact> findAll() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
#Override
#Transactional(readOnly = true)
public Contact findById(Long id) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
#Override
public Contact save(Contact contact) {
Contact contactB = new Contact();
contactB.setFirstName(contact.getFirstName());
contactB.setLastName(contact.getLastName());
if (contact.getId() == null)
{
emA.persist(contact);
emB.persist(contactB);
//throw new JpaSystemException(new PersistenceException());
}
else
{
emA.merge(contact);
emB.merge(contact);
}
return contact;
}
#Override
public long countAll() {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
}
foo/bar/domain/Contact.java:
package foo.bar.domain;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import static javax.persistence.GenerationType.IDENTITY;
#Entity
#Table(name = "contact")
#NamedQueries({
#NamedQuery(name = "Contact.findAll", query="select c from Contact c"),
#NamedQuery(name = "Contact.countAll", query="select count(c) from Contact c")
})
public class Contact implements Serializable{
private Long id;
private int version;
private String firstName;
private String lastName;
private Date birthDate;
public Contact()
{
}
//getters and setters
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Version
#Column(name = "VERSION")
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
#Column(name = "FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Temporal(TemporalType.DATE)
#Column(name = "BIRTH_DATE")
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
//other methods
public String toString()
{
return "Contact - Id: " + id + ", First name: " + firstName + ", Last name: " + lastName + ", Birthday: " + birthDate;
}
}
foo/bar/TxJtaSample.java:
package foo.bar;
import foo.bar.domain.Contact;
import foo.bar.service.ContactService;
import org.springframework.context.support.GenericXmlApplicationContext;
public class TxJtaSample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("tx-jta-app-context.xml");
ContactService contactService = ctx.getBean("contactService", ContactService.class);
Contact contact = new Contact();
contact.setFirstName("Jta");
contact.setLastName("Manager");
contactService.save(contact);
System.out.println("Contact saved successfully");
}
}
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>foo.bar</groupId>
<artifactId>SimpleProject26</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>SimpleProject26</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>3.2.3.RELEASE</spring.version>
<aspectj.version>1.7.2</aspectj.version>
</properties>
<dependencies>
<!-- Core Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Data -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
<!-- Commons Dbcp Driver -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>
<!-- MySql Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<!-- JUnit testing framework -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<!-- Logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.2</version>
</dependency>
<!-- Javax validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<!-- Joda time for Hibernate 4 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time-hibernate</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>3.1.0.CR6</version>
</dependency>
<!-- Google Guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>14.0.1</version>
</dependency>
<!-- AspectJ Framework -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<!-- Atomikos Transaction Framework -->
<dependency>
<groupId>com.atomikos</groupId>
<artifactId>transactions-jdbc</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>com.atomikos</groupId>
<artifactId>transactions-hibernate3</artifactId>
<version>3.8.0</version>
</dependency>
</dependencies>
<build>
<finalName>SpringApp</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*Tests.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
</project>
The output I get on my console is the following:
http://pastebin.com/VV8ukbwy
After testing your code, I made 3 modifications, all them in the tx-jta-app-context.xml configuration file, in the declaration of the emfBase bean:
I removed the key hibernate.transaction.factory_class, as explained in this page, when you work with JPA.
I removed the ${...} around the class com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup (maybe you have a variable defined in your project, but if you haven't, you should remove them).
I added a property to the jpaProperties: <prop key="javax.persistence.transactionType">jta</prop>. #Jukka told you in his comment to have a look at a document, and at the end, they say to add this property and it works for them.
After these modifications, it works for me (I can update the 2 databases and if I generate an error during the transaction, rollback is correctly executed in both databases). I give you here the resulting definition of the emfBase bean:
<bean id="emfBase" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" abstract="true">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="foo.bar.domain"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.transaction.manager_lookup_class">
com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup
</prop>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="javax.persistence.transactionType">jta</prop>
</props>
</property>
</bean>
I hope this can solve your problem.

Categories

Resources