How can I connect to two different databases, one for reading and one for writing in the same application using Spring? - spring

Use Case: I am running a spring application which has orders. I can create plans for these orders. My dev environment/db does not have any orders and they come from a different application (we share the same db). So, Is there a way I can read orders from production database but when I create a plan, it gets saved to dev database?
My persistence.xml is as below
<?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"
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="Demo_PU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.entity.ErrorMessage</class>
<class>com.entity.ErrorMessageTxt</class>
<class>com.entity.ErrorMessageTxtId</class>
<class>com.entity.Language</class>
<class>com.entity.TextEntity</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.InformixDialect" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.id.new_generator_mappings" value="true" />
<property name="hibernate.cache.region.factory_class"
value="net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory" />
<property name="hibernate.cache.use_second_level_cache"
value="true" />
<property name="hibernate.cache.use_query_cache" value="true" />
<property name="hibernate.generate_statistics" value="false" />
<property name="hibernate.connection.useUnicode" value="true" />
<property name="hibernate.connection.characterEncoding"
value="UTF-8" />
<!-- Adding timeouts for Lock Mode and Query -->
<property name="javax.persistence.query.timeout" value="60000" />
<property name="javax.persistence.lock.timeout" value="60000" />
</properties>
</persistence-unit>
</persistence>
My spring-config.xml is as below
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:component-scan base-package="com.project"/>
<context:component-scan base-package="com.project2"/>
<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:executor id="myExecutor"/>
<task:scheduler id="myScheduler"/>
<bean id="qa-informix" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/dcSysCommon"/>
</bean>
<bean id="pum" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
<property name="dataSources">
<map>
<entry key="localDataSource" value-ref="qa-informix" />
</map>
</property>
<property name="defaultDataSource" ref="qa-informix"/>
</bean>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="pum" />
<property name="jpaDialect">
<bean class="com.project.utils.IsolationSupportHibernateJpaDialect"/>
</property>
<property name="persistenceUnitName" value="PYD_PU" />
</bean>
<!-- bean post-processor for JPA annotations -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- this enables the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf" />
</bean>
<bean id="interpolator" class="org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator" />
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="messageInterpolator" ref="interpolator" />
</bean>
<bean class="com.project3.common.core.bo.LanguageBusinessObject" primary="true" />
<bean name="restUtils" class="com.project1.utils.RestUtils" />
<bean id="srvPropertyFile" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="srvPropertyFile" />
</bean>
<bean id="beanConfig" class="io.swagger.jaxrs.config.BeanConfig">
<property name="title" value="Swagger UI for QAS"/>
<property name="version" value="1.0.0" />
<property name="schemes" value="http" />
<property name="host" value="#{srvPropertyFile.hostName}:#{srvPropertyFile.pydPort}" />
<property name="basePath" value="planyourday/#{srvPropertyFile.countryCode}/#{srvPropertyFile.dcNumber}"/>
<property name="resourcePackage" value="com.project1.resources"/>
<property name="license" value="Apache 2.0 License"/>
<property name="licenseUrl" value="http://www.apache.org/licenses/LICENSE-2.0.html"/>
<property name="scan" value="true"/>
</bean>
<bean id="apiListingResource" class="com.project1.utils.SwaggerApiListingResource"/>
<bean id="swaggerSerializers" class="io.swagger.jaxrs.listing.SwaggerSerializers" scope="singleton"/>
</beans>
In my Jetty server config, I am defining the srvPropertyFile which references to the environment.properties file which has the database connection to dev db.
How should I manage my persistence context so that the entity manager used while reading orders and the entity manager used while creating plans connects to different databases?

you have to configure two persistence unit, data source and transaction manager(one for read and other for write) each.
While using entity manager specify the persistence unit like below.
PersistenceUnit(unitName = "x")
EntityManagerFactory entityManagerFactory;

Related

Spring JMS 4.1 + ActiveMQ handle stress request

Currently, My system is using Spring-jms 4.1.6 and ActiveMQ 5.2.0
We facing the issue is that when we have stress requests (50000 continuity requests like DDOS), the server is dying.
I think there are some problems with my config on the consumer side;
The config below is the original config
<?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:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd
">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
</bean>
<!-- Administrated objects -->
<bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory" destroy-method="destroy">
<property name="targetConnectionFactory">
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="failover:(tcp://localhost:${JMS_PORT})"/>
</bean>
</property>
<property name="reconnectOnException" value="false"/>
</bean>
<bean id="queue" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="test.service" />
</bean>
<!-- Message listener container for services -->
<bean id="errorHandler" class="com.myconsumer.test.LogErrorHandler"/>
<bean
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="queue" />
<property name="concurrentConsumers" value="10" />
<property name="maxConcurrentConsumers" value="20" />
<property name="messageListener" ref="serviceExporterDispatcher" />
<property name="errorHandler" ref="errorHandler" />
</bean>
<bean id="securityTokenVerificator" class="com.myconsumer.test.SecurityTokenVerificator">
<property name="authenticationService" ref="authenticationService" />
</bean>
<bean id="businessServiceInterceptor" class="com.myconsumer.test.RemoteInvocationBusinessServiceInterceptor">
<property name="securityTokenVerificator" ref="securityTokenVerificator" />
</bean>
<bean id="requestContextHandler" class="com.myconsumer.test.RequestContextHandler"/>
<bean id="remoteInvocationErrorHandler" class="com.myconsumer.test.RemoteInvocationErrorHandler" />
<bean id="serviceExporterDispatcher" class="com.myconsumer.test.ServiceExporterDispatcher">
<property name="businessServiceInterceptor" ref="businessServiceInterceptor" />
<property name="requestContextHandler" ref="requestContextHandler" />
<property name="remoteInvocationErrorHandler" ref="remoteInvocationErrorHandler" />
</bean>
</beans>
I tried with pool connection but it did not improve anything
<?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:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd
">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
</bean>
<!-- Administrated objects -->
<bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
<property name="connectionFactory">
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="failover:(tcp://localhost:${JMS_PORT})"/>
</bean>
</property>
<!-- <property name="reconnectOnException" value="false"/>
<property name="sessionCacheSize" value="3"/> -->
</bean>
<bean id="queue" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="test.service" />
</bean>
<!-- Message listener container for services -->
<bean id="errorHandler" class="com.myconsumer.test.LogErrorHandler"/>
<bean
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="pooledConnectionFactory" />
<property name="destination" ref="queue" />
<property name="concurrentConsumers" value="10" />
<property name="maxConcurrentConsumers" value="20" />
<property name="messageListener" ref="serviceExporterDispatcher" />
<property name="errorHandler" ref="errorHandler" />
</bean>
<bean
class="org.springframework.jms.config.DefaultJmsListenerContainerFactory">
<property name="concurrency" value="3-10"/>
</bean>
<bean id="securityTokenVerificator" class="com.myconsumer.test.SecurityTokenVerificator">
<property name="authenticationService" ref="authenticationService" />
</bean>
<bean id="businessServiceInterceptor" class="com.myconsumer.test.RemoteInvocationBusinessServiceInterceptor">
<property name="securityTokenVerificator" ref="securityTokenVerificator" />
</bean>
<bean id="requestContextHandler" class="com.myconsumer.test.RequestContextHandler"/>
<bean id="remoteInvocationErrorHandler" class="com.myconsumer.test.RemoteInvocationErrorHandler" />
<bean id="serviceExporterDispatcher" class="com.myconsumer.test.ServiceExporterDispatcher">
<property name="businessServiceInterceptor" ref="businessServiceInterceptor" />
<property name="requestContextHandler" ref="requestContextHandler" />
<property name="remoteInvocationErrorHandler" ref="remoteInvocationErrorHandler" />
</bean>
</beans>
Update config for Producer
<?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:jee="http://www.springframework.org/schema/jee" xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p"
xmlns:sec="http://www.springframework.org/schema/security" 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/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Initialize service invoker properties -->
<bean id="propertyPlaceHolder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties">
<bean factory-bean="resourceUtils" factory-method="getProperties">
<constructor-arg>
<bean factory-bean="resourceLoader"
factory-method="getResource">
<constructor-arg>
<value>service-invoker/service-invoker.properties</value>
</constructor-arg>
</bean>
</constructor-arg>
</bean>
</property>
</bean>
<!-- Administrated objects -->
<bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory" destroy-method="destroy">
<property name="targetConnectionFactory">
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="${broker.url}"/>
</bean>
</property>
</bean>
<bean id="queue" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="${service.queue}" />
</bean>
<!-- Service Locator -->
<bean id="serviceLocator" class="com.myproducer.test.service.impl.ApplicationServiceLocatorImpl">
<property name="authenticationService" ref="authenticationService"/>
</bean>
<!-- Services -->
<bean id="authenticationService"
class="com.myproducer.test.service.impl.ClientJmsInvokerProxyFactoryBean">
<property name="serviceInterface" value="com.myservicer.test.authentication.v1.AuthenticationService" />
<property name="connectionFactory" ref="connectionFactory" />
<property name="queue" ref="queue" />
<property name="receiveTimeout" value="${receiveTimeout}" />
</bean>
</beans>
Important
My 50000 request is sent frequently, I'm using nodejs to send and send the requests without waiting for the response to test the server.

Image not displayed in spring-boot version 1.5.3

I have been trying for more than an hour to display an image in my SpringBoot version 1.5.3 application.
I'm trying to display an image in my html page, which is the path:
And have used the image as:
<img src="images/DataServicesAdminAppLogo.png" width="40" height="40" class="d-inline-block align-top" alt="" hspace="10"/>
in my html page. But in vain. The image is not getting displayed.
Can someone please help?
UPDATE:
Network Inspector:
ApplicationContext.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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- <context:component-scan base-package="com.csaa.mdm"></context:component-scan> -->
<util:properties id="configLocProperties"
location="file:${app.config.home}/config/config.properties" />
<context:property-placeholder
location="file:${app.config.home}/config/config.properties" />
<bean id="configProperties"
class="com.csaa.mdm.adminApp.util.ApplicationPropertyConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="ignoreResourceNotFound" value="true" />
<property name="location">
<value>file:${app.config.home}/config/config.properties
</value>
</property>
</bean>
<bean id="applicationPropertyUtil" class="com.csaa.mdm.adminApp.util.ApplicationPropertyUtil">
<property name="propertyConfigurer" ref="configProperties" />
</bean>
<bean id="metaCryptoUtil" class="com.csaa.mdm.adminApp.util.CryptoUtil">
<property name="userId" value="${oracle.meta.username}"></property>
<property name="password" value="${oracle.meta.password}"></property>
<property name="key" value="123456789012345678901234"></property>
</bean>
<!-- Create datasource and give connection properties -->
<bean id="metaDatasource" primary="true"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${oracle.db.driver}" />
<property name="url" value="${oracle.db.dev.connection}" />
<property name="username" value="#{metaCryptoUtil.userId}" />
<property name="password" value="#{metaCryptoUtil.password}" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="metaDatasource" />
</bean>
<!-- Create the dao object and pass the datasource to it -->
<bean id="adminDao" class="com.csaa.mdm.adminApp.dao.AdminDao">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<bean id="adminUtil" class="com.csaa.mdm.adminApp.util.AdminUtil">
<property name="configProperties" ref="configLocProperties"></property>
</bean>
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate" />
</beans>

Error with Spring5+hibernate+jpa+hikaricp xml configuration

Please help. The below is my XML configuration file. My application runs properly. But it says no database selected when call database.
The exception looks like below:
2018-03-24 13:44:17 DEBUG SqlExceptionHelper:139 - could not extract ResultSet [n/a]
java.sql.SQLException: No database selected
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2794)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2322)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
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
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="app.sphi" />
<mvc:resources mapping="/res/**" location="/WEB-INF/res/" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<property name="poolName" value="springHikariCP" />
<property name="connectionTestQuery" value="SELECT 1" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/testdb?useUnicode=true" />
<property name="dataSourceClassName" value="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<!-- Create default configuration for Hibernate -->
<bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
</bean>
<!-- Configure the entity manager factory bean -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
<!-- Set JPA properties -->
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
</props>
</property>
<!-- Set base package of your entities -->
<property name="packagesToScan" value="app.sphi.model" />
<!-- Set share cache mode -->
<property name="sharedCacheMode" value="ENABLE_SELECTIVE" />
<!-- Set validation mode -->
<property name="validationMode" value="NONE" />
</bean>
<!-- Configure the transaction manager bean -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Enable annotation driven transaction management -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Configure Spring Data JPA and set the base package of the repository interfaces -->
<jpa:repositories base-package="app.sphi.repo"
transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory" />
</beans>
I will be pleased for any suggestion.
Do not configure both jdbcUrl and dataSourceClassName, pick one style or the other. In this case, I suggest you stick with jdbcUrl.

Conflicting persistence unit definitions exception

I am getting the following exception on server startup. I have just one persistence.xml in my project. Any ideas?
weblogic.application.ModuleException:
at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1520)
at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:484)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
Truncated. see log file for complete stacktrace
Caused By: java.lang.IllegalStateException: Conflicting persistence unit definitions for name 'TRAVEL_SYSTEM_UNIT': file:/D:/TravelSystem/workspace-sts/Travel_System-EAR/EarContent/APP-INF/classes/, file:/D:/TravelSystem/workspace-sts/Travel_System-dataaccess/target/classes/
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.preparePersistenceUnitInfos(DefaultPersistenceUnitManager.java:362)
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.afterPropertiesSet(DefaultPersistenceUnitManager.java:326)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:235)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
Truncated. see log file for complete stacktrace
My context file:
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation=" http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd">
<context:annotation-config />
<context:component-scan base-package="com.dataaccess" />
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/mysql" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="persistenceUnitName" value="SYSTEM_UNIT"></property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
<property name="packagesToScan" value="com.dataaccess.model"></property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
</property>
<!-- <property name="jpaVendorAdapter">
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true"></property>
<property name="showSql" value="true" />
</bean>
</property> -->
</bean>
<bean class="org.springframework.transaction.jta.JtaTransactionManager" id="transactionManager"/>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
</beans>
My persistence.xml file is in META-INF where it should be:
<?xml version="1.0" encoding="UTF-8" ?>
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="TRAVEL_SYSTEM_UNIT" transaction-type="JTA">
<jta-data-source>jdbc/mysql</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.max_fetch_depth" value="3" />
<property name="default_batch_fetch_size" value="25" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.generate_statistics" value="true" />
<!-- <property name="hibernate.hbm2ddl.auto" value="update"/> -->
<property name="hibernate.transaction.manager_lookup_class"
value="org.hibernate.transaction.SunONETransactionManagerLookup" />
</properties>
</persistence-unit>
</persistence>
using 3.1.2.RELEASE Maven 3.0.4
I just add below configuration to My context file:
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="pum"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath:META-INF/persistence-test.xml</value>
</list>
</property>
<property name="defaultDataSource" ref="dataSource"></property>
</bean>
On window I put META-INF/persistence.xml under src/java/resources.
Then I import same project to Ubuntu, this problem appeared. And it is fixed after I moved META-INF/persistence.xml to src/main/webapp.

PersistenceAnnotationBeanPostProcessor vs JpaVendorAdapter

I'm setting up a maven-spring-hibernate-mysql-tomcat environment.
I would like to inject my Entity manager using the #PersistenceContext annotation.
As I understand to do this, I should have PersistenceAnnotationBeanPostProcessor defined in my application context, pointing to my persistence.xml file.
In this case my application context could be looking like this more or less:
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task" xmlns:ox="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-3.1.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- Context -->
<context:component-scan base-package="com.yl.mypack" />
<!-- AOP -->
<aop:aspectj-autoproxy />
<!-- Properties -->
<context:property-placeholder
location="classpath:db.connection.properties,applicationProperties.properties" />
<!-- DB Connection Pool -->
<bean id="dataSourceGlobal" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<!-- Data Source -->
<property name="driverClass" value="${driverClass}" />
<property name="jdbcUrl" value="${jdbcUrl}" />
<property name="user" value="${user}" />
<property name="password" value="${password}" />
<!-- C3P0 Connection pool properties -->
<property name="minPoolSize" value="${c3p0.min_pool_size}" />
<property name="maxPoolSize" value="${c3p0.max_pool_size}" />
<property name="unreturnedConnectionTimeout" value="${c3p0.timeout}" />
<property name="idleConnectionTestPeriod" value="${c3p0.idle_test_period}" />
<property name="maxStatements" value="${c3p0.max_statements}" />
<property name="automaticTestTable" value="${c3p0.automatic_test_table}" />
</bean>
<!-- JPA -->
<!-- Creates a EntityManagerFactory for use with the Hibernate JPA provider -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
<property name="persistenceUnitName" value="myPU" />
<property name="dataSource" ref="dataSourceGlobal" />
</bean>
<!-- In order to enable EntityManager injection -->
<bean id="persistenceAnnotation"
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
<property name="persistenceUnits">
<map>
<entry key="myPU" value="classpath:META-INF/persistence.xml" />
</map>
</property>
</bean>
<!-- Transactions -->
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSourceGlobal" />
</bean>
</beans>
My persistence.xml could look like this:
<persistence-unit name="myPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.transaction.flush_before_completion"
value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
So now I guess I should be able to inject my entity manager using the #PersistenceContext annotation, at list this is what I get from the documentation. Before I'mm getting to JpaVendorAdapter, my first question would refer the entity manager factory definition:
The following properties:
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
<property name="persistenceUnitName" value="myPU" />
Are these required to be referred from the entity manager factory? Is it a must?
My second question would be regarding the JpaVendorAdapter, and in my case HibernateJpaVendorAdapter.
If I use HibernateJpaVendorAdapter, do I still need to have a persistence.xml file? Since some of the properties are overlapping. Moreover, do I still need to have PersistenceAnnotationBeanPostProcessor defined, pointing to my persistence.xml file? Can these 2 go together (PersistenceAnnotationBeanPostProcessor and HibernateJpaVendorAdapter)? Should they go together? What is the best practice, assuming I'm avoiding any JDNI style definitions?
Thanks in advance
The combination of data source bean and HibernateJpaVendorAdapter allows you to get rid of persistence.xml with Spring 3.1. Check out this article:
http://www.baeldung.com/2011/12/13/the-persistence-layer-with-spring-3-1-and-jpa/
So the answers:
They are not a must.
No, you don't need to have a persistence.xml.
I am not exactly sure of what use PersistenceAnnotationBeanPostProcessor is.
<context:component-scan base-package="com.demo.dao" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="hibernate-resourceLocal"/>
</bean>
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
My Spring application context xml looks as simple as this. And it is working.
I don't what the best practice is, but I will keep persistence.xml so that in case I need to expose my service as session bean, it can be easily done.

Resources