How to inject #PersistenceContext in DAO generated by Hibernate3-maven-plugin - spring

I wanna create a Java Application based on Hibernate-3 and Spring Framework. To get the process easy I found hibernate3-maven-plugin that is able to perform reverse-engineering of the existing database.
Here there's example of POM:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>hibernate3-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<components>
<component>
<name>hbm2java</name>
<outputDirectory>src/main/java</outputDirectory>
<implementation>jdbcconfiguration</implementation>
</component>
<component>
<name>hbm2dao</name>
<outputDirectory>src/main/java</outputDirectory>
<implementation>jdbcconfiguration</implementation>
</component>
</components>
<componentProperties>
<revengfile>/src/main/resources/model.reveng.xml</revengfile>
<propertyfile>/src/main/resources/hibernate.properties</propertyfile>
<jdk5>true</jdk5>
<ejb3>true</ejb3>
</componentProperties>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.1_3</version>
</dependency>
</dependencies>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>hbm2java</goal>
<goal>hbm2dao</goal>
</goals>
</execution>
</executions>
</plugin>
Then I set up the context of Spring:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="gomer" />
</bean>
<bean id="entityManager" factory-bean="entityManagerFactory" factory-method="createEntityManager"/>
<bean id="user" class="ru.tomtrix.first.db.UserHome">
<property name="entityManager" ref="entityManager"/>
</bean>
</beans>
It perfectly generates an Entity file and a DAO file except the following. In DAO file there's a EntityManager:
#Stateless
public class UserHome {
private static final Log log = LogFactory.getLog(UserHome.class);
#PersistenceContext private EntityManager entityManager;
... and this field hasn't got a setter! Eventually Spring throws the exception:
Invalid property 'entityManager' of bean class [ru.tomtrix.first.db.UserHome]: Bean property 'entityManager' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
Of course it's not a good practice to write the setter manually. I think there is a way to inject a manager properly.
So how to do it without rewriting the generated file?
Corresponding information:
1) I'd like to create a stand alone application (and possibly run it in an Application Server like Tomcat)
2) model.reveng.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering SYSTEM "http://www.hibernate.org/dtd/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
<table-filter match-name=".*" package="ru.tomtrix.first.db"/>
</hibernate-reverse-engineering>
3) persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="gomer" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>User</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="1234"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/users"/>
</properties>
</persistence-unit>
</persistence>

The problem is you are missing a part of the configuration. You need to tell Spring that you want to (also) use annotations for configuration. For this add the <context:annotation-config /> to your configuration and remove the setting of the entityManager
Next to that remove the calling of the factory method spring will handle all that for you.
Added tip use the version-less schemas insead of
<?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"
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">
<context:annotation-config />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="gomer" />
</bean>
<bean id="user" class="ru.tomtrix.first.db.UserHome" />
</beans>
Your code might be problematic when you deploy it to a fullblown app server and you might run into issues with Spring and the EJB container competing over control of the beans. The hibernate plugin generates #Stateless session beans which in general will be picked up by the app. server (depending on which one you use).

Related

mbeanExporter Invocation of init method failed UnableToRegisterMBeanException… is javax.management.InstanceAlreadyExistsException

I am getting "mbeanExporter Invocation of init method failed UnableToRegisterMBeanException… InstanceAlreadyExistsException" while trying to start a very simple Spring Batch Admin application in Websphere 8. The entire application can be downloaded from https://examples.javacodegeeks.com/enterprise-java/spring/spring-batch-admin-tutorial/.
This is a very simple Spring Batch Admin project with only one very simple job. I can successfully debug the project in Eclipse and I can build the war, deploy it to Websphere Liberty Profile 8.5 successfuly. By success I mean I can open the Spring Batch Admin console and trigger the job properly.
The error below I am getting only when I move such war to Mainframe Websphere 8.5 ND. I don't think it is direct related to mainframe/unix. In fact, I am wondering if it is not a conflict between the libraries described below in my Pom.xml and Websphere. Any idea what to check will be extremely appreciatted. Recently, I have certain issue when using Hibernate/JPA and by simply downgrade a bit the version fix the error. It was a bit similar scenario: works in Websphere Liberty Profile but didn't work in Websphere 8.5 ND until I downgrade the hibernate version in my pom.xml. Well, this time there is no hibernate at all but I typed here what fixed sometime ago and maybe it can help someone to give me some idea what to check. I have a scratch idea that it is library conflict but I don't know what to check or investigate.
I saw few people getting similar error by using Spring Boot but that isn't my case at all. Specially in Getting exception while refreshing Spring ApplicationContext in Spring Boot application someone got exactly same error as me after added
#EnableIntegrationMBeanExport(registration = RegistrationPolicy.REPLACE_EXISTING)
Nevertheless, I don't have any anotation in such project and I am not using EnableIntegrationMBeanExport at least explicitly. Maybe it is been used behind the scene but I am not that expert on it so if someone can give me possibilities to check it will be an excellent north. Additionally, I am not using Spring MVC.
Error when startuping the application
Trace: 2016/09/09 22:49:17.049 02 t=9BDE88 c=UNK key=P8 tag= (13007004)
SourceId: com.ibm.ws.webcontainer.webapp.WebApp.logServletError
ExtendedMessage: BBOO0220E: SRVE0293E: ÝServlet Error¨-ÝBatch Servlet¨: org.springframework.beans.factory.BeanCreationException: E
rror creating bean with name 'mbeanExporter': Invocation of init method failed; nested exception is org.springframework.jmx.export.U
nableToRegisterMBeanException: Unable to register MBean Ýorg.springframework.integration.monitor.IntegrationMBeanExporter#4ed60bcf¨
with key 'integrationMBeanExporter'; nested exception is javax.management.InstanceAlreadyExistsException: spring.application:cell=dt
l85cel,name=integrationMBeanExporter,type=IntegrationMBeanExporter,node=wlemyAppa,process=WLEmyApp
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.j
ava:1553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.jav
a:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:
475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:70
3)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:7
60)
...
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanSe
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:814)
at com.ibm.ws390.management.connector.corba.CorbaConnectorImpl.invoke(CorbaCon
at com.ibm.ws390.management.connector.corba._CorbaConnectorImplBase._invoke(_C
at com.ibm.ws390.orb.CommonBridge.invoke(CommonBridge.java:1898)
at com.ibm.ws390.orb.CommonBridge.getAndProcessWork(CommonBridge.java:725)
at com.ibm.ws390.orb.CommonBridge.runApplicationThread(CommonBridge.java:614)
at com.ibm.ws390.management.connector.corba.CorbaConnectorImpl.invoke(CorbaCon
at com.ibm.ws390.management.connector.corba._CorbaConnectorImplBase._invoke(_C
at com.ibm.ws390.orb.CommonBridge.invoke(CommonBridge.java:1898)
at com.ibm.ws390.orb.CommonBridge.getAndProcessWork(CommonBridge.java:725)
at com.ibm.ws390.orb.CommonBridge.runApplicationThread(CommonBridge.java:614)
at com.ibm.ws.util.ThreadPool$ZOSWorker.run(ThreadPool.java:2116)
Caused by: org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean Ýorg.springframework.integration.
monitor.IntegrationMBeanExporter#4ed60bcf¨ with key 'integrationMBeanExporter';nested exception is javax.management.InstanceAlready
ExistsException: spring.application:cell=mycel,name=integrationMBeanExporter,type=IntegrationMBeanExporter,node=wlemyAppa,process=
WLEmyApp
pom.xml
<spring.version>4.0.5.RELEASE</spring.version>
<spring.batch.version>3.0.4.RELEASE</spring.batch.version>
<spring.jdbc.version>4.0.5.RELEASE</spring.jdbc.version>
<hsql.version>1.8.0.7</hsql.version>
<commons.version>1.4</commons.version>
<spring.oxm.version>4.0.5.RELEASE</spring.oxm.version>
<spring.batch.admin>1.3.1.RELEASE</spring.batch.admin>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
<version>${spring.batch.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsql.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.jdbc.version}</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>${commons.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.oxm.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-admin-manager</artifactId>
<version>${spring.batch.admin}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-context-support</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-admin-resources</artifactId>
<version>${spring.batch.admin}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-context-support</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<finalName>SpringBatchAdmin</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Job-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch" xmlns:util="http://www.springframework.org/schema/util"
xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:batch-default.properties
</value>
</list>
</property>
<property name="searchSystemEnvironment" value="true" />
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>
<job id="myjob" xmlns="http://www.springframework.org/schema/batch"
restartable="true">
<step id="myStep" allow-start-if-complete="true">
<tasklet>
<chunk reader="cvsFileItemReader" writer="itemWriter"
commit-interval="1000" />
</tasklet>
</step>
</job>
<bean id="cvsFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
<!-- property name="resource" value="${INPUT_FILE_LOCATION}"></property-->
<property name="resource" value="file:/C:/temp/sampleData.csv"></property>
<property name="linesToSkip" value="1"></property>
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean
class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<!-- <property name="names" value="${INCOMING_COLUMN_MAPPING}"></property> -->
<property name="names" value="firstName,lastName,city,id"></property>
</bean>
</property>
<property name="fieldSetMapper">
<bean
class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="prototypeBeanName" value="userModel"></property>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="itemWriter"
class="org.springframework.batch.item.database.JdbcBatchItemWriter">
<property name="dataSource" ref="dataSource"></property>
<property name="sql" value="${INSERT_QUERY}">
</property>
<property name="itemSqlParameterSourceProvider">
<bean
class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider" />
</property>
</bean>
<bean id="userModel" class="com.javacodegeeks.example.util.UserModel"
scope="prototype" />
</beans>
Contex-config.xml
<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"
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.xsd">
<!-- using in-memory store for batch meta-data -->
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="transactionManager" />
<property name="databaseType" value="hsql" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
lazy-init="true" destroy-method="close">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url"
value="jdbc:hsqldb:file:src/main/resources/hsqldb/batchcore.db;shutdown=true;" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
</beans>
**** Edited:
I am reading Deploying two Spring batch applications in same cluster in a single Weblogic Domain? which explain how to make two Spring Batch Admin run in Weblogic.
I can see that the person was facing exactly same issue. After that I created another Spring Batch Admin and deployed to my local Websphere Liberty Profile then I got exact same error I was picking up in mainframe.
Firstly it made happy because I thought I finally found the problem and solution.
I fixed in my local websphere by adding /META-INF/spring/batch/override/jmx-context.xml with:
<?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:int-jmx="http://www.springframework.org/schema/integration/jmx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/integration/jmx http://www.springframework.org/schema/integration/jmx/spring-integration-jmx.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<int-jmx:mbean-export id="integrationMBeanExporter" default-domain="SpringBatchAdmin" server="mbeanServer" />
<context:mbean-export default-domain="SpringBatchAdmin" server="mbeanServer" />
</beans>
Well that was great news untill I tried same approach in Websphere 8.5 ND running in mainframe. Exactly same issue remains there. Please, I am desparetly looking for anything else I can at least try.
had the same problem.
I have virtual hosting on the same machine where spring integration was used. Once deployed the test system everything was Ok. After a while, I deployed the prod system and all went wrong.
I specified at Application.class the following:
#EnableIntegrationMBeanExport(defaultDomain = "${managed.domain}")
and in the application.properties file I defined managed.domain the name.
The solution I've found here:
Tutorial

Separate DB just for JUnit tests in Spring app

I am writing unit tests for my Spring application using in-file HSQL db. I don't want to pollute this db with test data, so I am trying to set up another in-memory HSQL db instance to be used in tests.
In my abstract testing class I import test application context XML configuration:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("/testingContext.xml")
#Transactional
public abstract class AbstractDaoForTesting {
testingContext.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
">
<jdbc:embedded-database id="dataSource" type="HSQL" />
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.se.micom" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf" />
</bean>
<tx:annotation-driven />
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="characteristicDao" class="com.se.micom.dao.CharacteristicDaoImpl"/>
<bean id="functionalityDao" class="com.se.micom.dao.FunctionalityDaoImpl"/>
<bean id="segmentDao" class="com.se.micom.dao.SegmentDaoImpl"/>
<bean id="segmentService" class="com.se.micom.service.SegmentServiceImpl"/>
<bean id="functionalityService" class="com.se.micom.service.FunctionalityServiceImpl"/>
<bean id="characteristicService" class="com.se.micom.service.CharacteristicServiceImpl" />
</beans>
Up to now in-memory HSQL db is working fine in test.
However, as soon as I introduce in my project persistence.xml in src/main/resources/META-INF unit tests start to use this persistence unit and not the one from testingContext.xml.
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="micomPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.se.micom.dao.domain.Characteristic</class>
<class>com.se.micom.dao.domain.Functionality</class>
<class>com.se.micom.dao.domain.Segment</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:file:D:\workspace_java\Micom2\db\micom"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
</properties>
</persistence-unit>
</persistence>
What's wrong with this configuration? Why tests "prefer" to use db defined in persistence.xml?
Your problem is a perfect example for Spring profiles. It is always problematic to have multiple beans doing the same thing in your context at once if you want a certain one to be used.
You should have two different profiles, "prod" and "test", and wrap your bean declaration in the xml config accordingly with <beans profile="XYZ"> ... </beans>. A more extensive example can be found here.
You can then annotate your test with #Profile("test") and it should use the correct database.

maven build helper plugin issue

I'm using maven build helper to automatically add integration-test/java and integration-test/resources folders to my project classpath. It works great when I run my tests with JUnit in Eclipse, but got a problem when I ran the web project where Tomcat always pick up the test resources instead of the production one.
My project structure is something like this:
DaoProject
src/main/resources/datasource.properties
src/main/resources/spring-data.xml
src/main/java/....
WebProject
src/main/resources/appContext.xml
src/integration-test/java/com/mypkg/controller/MyControllerIT.java
src/integration-test/resources/datasource.properties
The appContext.xml imports spring-data.xml which in turn loads datasource.properties as a propterties source place holder.
appContext.xml contents:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" 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/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:annotation-config />
<tx:annotation-driven/>
<context:component-scan base-package="com.mypkg" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"
p:defaultEncoding="UTF-8">
<property name="basenames">
<array>
<value>messages</value>
</array>
</property>
</bean>
<import resource="classpath:datasource.xml" />
datasource.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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"
>
<context:property-placeholder location="classpath:datasources.properties"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="${config.db.url}" />
<property name="username" value="${config.db.username}" />
<property name="password" value="${config.db.password}" />
pom.xml:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<id>add-integration-test-sources</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>src/integration-test/java</source>
</sources>
</configuration>
</execution>
<execution>
<id>add-integration-test-resources</id>
<phase>generate-test-resources</phase>
<goals>
<goal>add-test-resource</goal>
</goals>
<configuration>
<resources>
<resource>
<directory>src/integration-test/resources</directory>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
I think that the problem is with the way you load the datasource.properties file. Try specifying the entire path in the location attribute of the PropertyPlaceholderConfigurer:
<context:property-placeholder location="classpath:src/main/resources/datasources.properties"/>
Hope this helps.

Spring jpa(Hibernate) with tomcat

I'm working with JPA(Hibernate) and spring project these days, I configured spring, jpa and try to deploy the application on tomcat7, As I know jpa/hibernate creates tables using entity class first loading, but here I couldn't see any connection between database and application when applications starts, below you can see my configuration,I have seen lot of questions posted regarding this matter, I couldn't find the proper solution to my problem.
Can any one tell me what is the problem here.I have created a application without any issues in jetty server sometime back,
Thank you in advance
applicationContext-dao.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
default-lazy-init="true">
<!-- Use #Transaction annotations for managing transactions -->
<!--<tx:annotation-driven/>-->
<!-- holding properties for database connectivity / -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<tx:annotation-driven proxy-target-class="true" />
<!-- Activates scanning of #Autowired -->
<context:annotation-config/>
<!-- Activates scanning of #Repository -->
<context:component-scan base-package="lk.gov.elg"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"
p:dataSource-ref="dataSource"/>
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"
p:jpaVendorAdapter-ref="jpaAdapter">
<property name="persistenceUnitName" value="eLGPersistenceUnit"></property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver"/>
</property>
</bean>
<!-- Jpa adapter for the Hibernate -->
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:databasePlatform="org.hibernate.dialect.MySQLDialect"
p:generateDdl="true"
p:showSql="true" >
</bean>
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>
persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="eLGPersistenceUnit"
transaction-type="RESOURCE_LOCAL">
<!--transaction-type="JTA">-->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.hbm2ddl.auto" value="validate"/>
</properties>
<!--<provider>org.hibernate.ejb.HibernatePersistence</provider>-->
</persistence-unit>
</persistence>
I think there is no issue with your configuration, try after removing "default-lazy-init=true" attribute
Cheers
try changing:
<property name="hibernate.hbm2ddl.auto" value="validate"/>
to:
<property name="hibernate.hbm2ddl.auto" value="update"/>
or:
<property name="hibernate.hbm2ddl.auto" value="create"/>

spring-simple-memcache - maven dependencies for ReadThroughSingleCache

Has anyone used spring simple memcached? I have not been able to get the exact maven dependency and the repository where this is available.
The dependencies mentioned on the code.google page (http://code.google.com/p/simple-spring-memcached/) mention other dependencies but it does not include jar for Simple-spring-memcache itself.
Thanks for the help guys.
Try this one:
<dependency>
<groupId>com.google.code.simple-spring-memcached</groupId>
<artifactId>simple-spring-memcached</artifactId>
<version>2.0.0</version>
</dependency>
In case of SSM 2.0.0 you need also memcached client (xmemcached or spymemcached):
<dependency>
<groupId>com.google.code.simple-spring-memcached</groupId>
<artifactId>simple-spring-memcached</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.googlecode.xmemcached</groupId>
<artifactId>xmemcached</artifactId>
<version>1.3.5</version>
</dependency>
and configure connection to local memcached server:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<import resource="simplesm-context.xml" />
<aop:aspectj-autoproxy />
<bean name="defaultMemcachedClient" class="com.google.code.ssm.CacheFactory">
<property name="cacheClientFactory">
<bean class="com.google.code.ssm.providers.xmemcached.MemcacheClientFactoryImpl" />
</property>
<property name="addressProvider">
<bean class="com.google.code.ssm.config.DefaultAddressProvider">
<property name="address" value="127.0.0.1:11211" />
</bean>
</property>
<property name="configuration">
<bean class="com.google.code.ssm.providers.CacheConfiguration">
<property name="consistentHashing" value="true" />
</bean>
</property>
</bean>
</beans>

Resources