Error creating bean with name 'CommonsConfigurationFactoryBean' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: - tomcat8

I'm having the error that I think is connected to PostgreSQL-Tomcat connection. I was not able to locate the piece where I am mistaken:
My catalina.out:
23.10.2020 14:45:27.207 [localhost-startStop-1] WARN o.s.w.c.support.XmlWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.support.PropertySourcesPlaceholderConfigurer#0': Cannot resolve reference to bean 'CommonsConfigurationFactoryBean' while setting bean property 'properties'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CommonsConfigurationFactoryBean' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'DatabaseConfiguration' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'psqlDataSource' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is javax.naming.NamingException: Could not create resource factory instance [Root exception is java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSourceFactory]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:334) ~[spring-beans-3.2.13.RELEASE.jar:3.2.13.RELEASE]
...........
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CommonsConfigurationFactoryBean' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'DatabaseConfiguration' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'psqlDataSource' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is javax.naming.NamingException: Could not create resource factory instance [Root exception is java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSourceFactory]
.........
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'psqlDataSource' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is javax.naming.NamingException: Could not create resource factory instance [Root exception is java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSourceFactory]
My applicationcontext:
<?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-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean id="psqlDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/freshSiteDS"/>
<property name="lookupOnStartup" value="true"/>
<property name="proxyInterface" value="javax.sql.DataSource"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="psqlDataSource"/>
</bean>
<bean id="flyway" class="com.googlecode.flyway.core.Flyway" init-method="migrate" depends-on="psqlDataSource">
<property name="dataSource" ref="psqlDataSource"/>
<property name="initOnMigrate" value="true"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="psqlDataSource" />
</bean>
<bean id="namedJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="psqlDataSource" />
</bean>
<bean id="objectMapper" class="org.codehaus.jackson.map.ObjectMapper">
<property name="propertyNamingStrategy" value="#{T(org.codehaus.jackson.map.PropertyNamingStrategy).CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES}" />
</bean>
<context:property-placeholder file-encoding="UTF-8" properties-ref="CommonsConfigurationFactoryBean" ignore-resource-not-found="true" ignore-unresolvable="true"/>
<bean name="CommonsConfigurationFactoryBean"
class="org.springmodules.commons.configuration.CommonsConfigurationFactoryBean">
<constructor-arg ref="DatabaseConfiguration"/>
</bean>
<bean name="DatabaseConfiguration"
class="org.apache.commons.configuration.DatabaseConfiguration" depends-on="flyway">
<constructor-arg type="javax.sql.DataSource" ref="psqlDataSource"/>
<constructor-arg index="1" value="st_application_properties"/>
<constructor-arg index="2" value="property_key"/>
<constructor-arg index="3" value="property_value"/>
</bean>
<import resource="kernel-context.xml"/>
<import resource="service-context.xml"/>
<import resource="security-context2.xml"/>
<import resource="ws-context.xml"/>
<import resource="settings-context.xml"/>
<import resource="migration-context.xml"/>
<import resource="search-context.xml"/>
</beans>
The JDBC driver is in /opt/tomcat/lib/postgresql-42.2.18.jar
Please, give some piece of advice

Related

How to customize ChatMessageListeningEndpoint & ChatMessageSendingMessageHandler for GCM using spring integration?

Working on customizing ChatMessageListeningEndpoint & ChatMessageSendingMessageHandler but facing issues like
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myNotificationListeningEndpoint' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: outputChannel is required
<int:channel id="gcmInboundNotificationChannel"/>
<int:channel id="gcmOutboundNotificationChannel"/>
<bean id="toGcmTransformer" class="com.test.cardhash.service.AndroidMessageTransformer"/>
<int:chain input-channel="gcmOutboundNotificationChannel">
<bean class="com.test.cardhash.service.MyMessageSendingMessageHandler">
<constructor-arg ref="gcmConnection" />
</bean>
</int:chain>
<int:transformer id="testTransformer" ref="toGcmTransformer" input-channel="gcmInboundNotificationChannel"
method="doTransform" output-channel="gcmOutboundNotificationChannel"/>
<int-xmpp:outbound-channel-adapter
id="gcmOutboundAdapter" channel="gcmOutboundNotificationChannel"
xmpp-connection="gcmConnection" auto-startup="true"/>
<int:chain input-channel="gcmInboundNotificationChannel">
<bean class="com.test.cardhash.service.MyNotificationListeningEndpoint">
<constructor-arg ref="gcmConnection" />
<property name="outputChannel" ref="gcmOutboundNotificationChannel" />
</bean>
</int:chain>
<int-xmpp:inbound-channel-adapter
id="gcmInboundAdapter" channel="gcmInboundNotificationChannel"
xmpp-connection="gcmConnection" extract-payload="true" auto-startup="true" />

How to load bean without using ApplicationContext or ClassPathXmlApplicationContext in SpringData JPA

I am new to spring Data JPA.I facing problem in loading bean without using ApplicationContext or ClassPathXmlApplicationContext.Because in my current project I have one old spring related jar which cannot be removed.Because of which my current "SpringContext.xml" cannot be loaded.Here is my code which prevent from loading SpringContext.xml
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("SpringContext.xml");
RegistrationBean registrationBean = (RegistrationBean)context.getBean("registrationBean");
Here is my RegistrationBean for my Repository
#Component
public class RegistrationBean {
#Autowired
private CreditorProfileRepository creditorProfileReposigtory;
public RegistrationBean(){
}
public CreditorProfileRepository getCreditorProfileReposigtory() {
return creditorProfileReposigtory;
}
public void setEmployeeReposigtory(CreditorProfileRepository creditorProfileReposigtory) {
this.creditorProfileReposigtory = creditorProfileReposigtory;
}
}
Here is my repository
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface CreditorProfileRepository extends CrudRepository <CreditorProfile, String>{
public CreditorProfile findBympcreditorprofileidpk(String mpcreditorprofileidpk);
}
So I taught of using constructor injection to load registrationBean in my application class.Here is my application class
public class CreateCreditorProfile implements ICreateCreditorProfile{
RegistrationBean repositoryRegistration;
CreateCreditorProfile(RegistrationBean repositoryRegistration){
this.repositoryRegistration=repositoryRegistration;
}
CreateCreditorProfile(){
this.repositoryRegistration=repositoryRegistration;
}
#Override
public void createCreditorProfile(CreditorProfileServiceDetails creditorProfileServiceDetails) {
CreditorProfile creditorProfile = new CreditorProfile();
creditorProfile.setcreditorprofileidpk("343243243");
creditorProfile.setpartyid("000005");
creditorProfile.setpartyname("Federico o Peluso");
repositoryRegistration.getCreditorProfileReposigtory().save(creditorProfile);
}
Here is my ApplicationContext.xml
<bean id="registrationBean" class="com.mi.bn.payment.persistence.RegistrationBean" scope="prototype" />
<bean id="CreateCreditorProfile" class="com.mi.bn.paymen.persistence.CreateCreditorProfile" scope="prototype" >
<constructor-arg name="repositoryRegistration" ref="registrationBean" />
</bean>
<bean id="creditorsProfileConfiguration" class="com.mi.bn.payment.domain.configuration.CreditorsProfileConfiguration" scope="prototype">
<constructor-arg name="creater" ref="CreateCreditorProfile" />
</bean>
Here is my SpringContext.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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<!-- For consider the using of annotations foe defining Spring Bean -->
<context:annotation-config />
<!-- For defining Spring Bean -->
<context:component-scan base-package="com.cs.ed.paymentmessaging.persistence" />
<!-- For bootstrapping the Spring Repository -->
<jpa:repositories base-package="com.cs.ed.paymentmessaging.persistence" />
<!-- Necessary to get the entity manager injected into the factory bean -->
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="url" value="jdbc:db2://localhost:50000/DD23"/>
<property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver"/>
<property name="username" value="db2admin"/>
<property name="password" value="Wasadm1n"/>
</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.DB2Dialect"/>
</bean>
<!-- Entity Manager Factory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="SpringData"></property>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Enable Transactional Manner -->
<tx:annotation-driven transaction-manager="transactionManager" />
But still it is my application class I get null pointer exception at
repositoryRegistration.getCreditorProfileReposigtory().save(creditorprofile)
So Please let me know workaround for this problem.
Here is stack trace
11:03:04,725 INFO [CommandExecuter] An Unexpected Error Occurred An Unexpected Error Occurred java.lang.NullPointerException
com.trapedza.bankfusion.core.BankFusionException: An Unexpected Error Occurred java.lang.NullPointerException
at com.misys.bankfusion.subsystem.microflow.runtime.command.ExecuteMicroflowCommand.createBankFusionException(ExecuteMicroflowCommand.java:1224)
at com.misys.bankfusion.subsystem.microflow.runtime.command.ExecuteMicroflowCommand.execute(ExecuteMicroflowCommand.java:674)
at com.misys.bankfusion.command.impl.AbstractCommand.execute(AbstractCommand.java:596)
at com.trapedza.bankfusion.servercommon.commands.AbstractCommand.execute(AbstractCommand.java:392)
at com.misys.bankfusion.command.impl.CommandExecuter.executeCommand(CommandExecuter.java:435)
at com.misys.bankfusion.controller.ExecutionModeHelper.executeDirect(ExecutionModeHelper.java:142)
at com.misys.bankfusion.controller.ExecutionModeHelper.executeCommand(ExecutionModeHelper.java:121)
at com.misys.bankfusion.controller.ExecutionController.executeCommand(ExecutionController.java:121)
at com.misys.bankfusion.controller.CommandUtils.executeCommand(CommandUtils.java:66)
at com.misys.bankfusion.uxp.plugin.BankFusionServicePlugin.processOtherRequests(BankFusionServicePlugin.java:799)
at com.misys.bankfusion.uxp.plugin.BankFusionServicePlugin.executeService(BankFusionServicePlugin.java:191)
at com.misys.uxp.container.servlet.UXServlet.service(UXServlet.java:104)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.NullPointerException
at com.misys.bankfusion.paymentmessaging.persistence.CreateCreditorProfile.createCreditorProfile(CreateCreditorProfile.java:65)
at com.misys.bankfusion.paymentmessaging.domain.configuration.CreditorsProfileConfiguration.createCreditorProfile(CreditorsProfileConfiguration.java:34)
at com.misys.bankfusion.paymentmessaging.controller.fatom.MaintainCreditorProfiles.process(MaintainCreditorProfiles.java:46)
Your RegistrationBean seems not to be autowired:
public class CreateCreditorProfile implements ICreateCreditorProfile{
#Autowired
RegistrationBean repositoryRegistration;
...
}
Regarding your question why the constructor call is not working, as far as I can see there are 2 context.xml declarations - ApplicationContext.xml and SpringContext.xml. You need to load both of them:
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"SpringContext.xml","ApplicationContext.xml");
Or you can import the Application.xml inside the SpringContext.xml
<import resource="ApplicationContext.xml" />
Both ways should result in loading your beans properly.

Spring Data JPA + Eclipselink + Autowiring

I have this little project that works with Hibernate + Spring JPA and I'm just trying to change Hibernate to EclipseLink. When I do that, my jUnit test case simply can't autowire the very same repository that works with Hibernate. I can't figure out what is wrong...
application-context.xml
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/test" />
<property name="username" value="root" />
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasource" />
<property name="persistenceUnitName" value="persistenceEclipseLink" />
<property name="jpaDialect" ref="jpaDialect" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter" />
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver" />
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<jpa:repositories base-package="com.example.test.repositories"></jpa:repositories>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
persistence.xml
<persistence-unit name="persistenceHibernate"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
<persistence-unit name="persistenceEclipseLink"
transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.example.test.entities.Post</class>
</persistence-unit>
This will result in:
ERROR org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener[org.springframework.test.context.support.DependencyInjectionTestExecutionListener#2c5af885] to prepare test instance [com.example.test.PostRepositoryTest#871fa83] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.example.test.PostRepositoryTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.example.test.repositories.PostRepository com.example.test.PostRepositoryTest.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'postRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: The type [null] is not the expected [ManagedType] for the key class [class com.example.test.entities.Post].
If I simply change my entityManagerFactory to the bellow, everything works (using Hibernate):
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasource" />
<property name="persistenceUnitName" value="persistenceHibernate" />
</bean>
Can anyone catch what am I doing wrong on the EclipseLink configuration?
Thanks in advance.
EDIT:
Here's my jUnit test case:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations="classpath:META-INF/application-context.xml")
public class PostRepositoryTest {
#Autowired
PostRepository repository;
#Test
public void test() {
Post post = new Post();
post.setPostTitle("title");
repository.save(post);
}
}
EDIT
Full stack trace:
3601 [main] ERROR org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#6077e77a] to prepare test instance [com.example.test.PostRepositoryTest#2d2e3a2c]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.example.test.PostRepositoryTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.example.test.repositories.PostRepository com.example.test.PostRepositoryTest.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'postRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: The type [null] is not the expected [ManagedType] for the key class [class com.example.test.entities.Post].
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.example.test.repositories.PostRepository com.example.test.PostRepositoryTest.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'postRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: The type [null] is not the expected [ManagedType] for the key class [class com.example.test.entities.Post].
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 26 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'postRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: The type [null] is not the expected [ManagedType] for the key class [class com.example.test.entities.Post].
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:149)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:102)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1442)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:248)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:876)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:818)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:735)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 28 more
Caused by: java.lang.IllegalArgumentException: The type [null] is not the expected [ManagedType] for the key class [class com.example.test.entities.Post].
at org.eclipse.persistence.internal.jpa.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:424)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:58)
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:65)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:149)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:87)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:70)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:137)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:125)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:41)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:142)
... 36 more
Post.java
#Entity
#Table(name="POST")
public class Post {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID")
Integer postId;
#Column(name="TITLE")
String postTitle;
(...getters and setters...)
}
PostRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.test.entities.Post;
public interface PostRepository extends JpaRepository<Post, Integer> {
}
Can you please include the full exception stack trace, (also the mappings for the Post class)
To use the same properties as you have in Hibernate,
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true" />
in EclipseLink this would be,
<property name="eclipselink.target-database" value="MySQL" />
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.logging.level" value="fine" />

Eclipselink & Spring Data

I am trying to implement a solution using a combination of eclipselink (2.4.0) and spring-data-jpa (1.1.0.RELEASE). However, every time I deploy the solution (Tomcat 7), I get the following exception:
Caused by: java.lang.IllegalArgumentException: No [ManagedType] was found for
the key class [com.acme.domain.entities.User] in the Metamodel - please
verify that the [Managed] class was referenced in persistence.xml using a
specific <class>com.acme.domain.entities.User</class> property or a global
<exclude-unlisted-classes>false</exclude-unlisted-classes> element.
It appears to occur when the repository autowiring takes place (code examples below):
Service class
#Component
public class UserDataService {
#Autowired
private UserRepository userRepository;
...
}
Entity class
package com.acme.domain.entities;
...
#Entity
#Table(name = "users")
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
private Integer id;
...
}
persistence.xml
<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.acme.domain.entities.User</class>
...
</persistence-unit>
Can this be due to some conflict between spring and eclipselink?
UPDATE:
Stacktrace...
[#|2012-07-31 16:25:02,317|ERROR|pool-2-thread-40|org.springframework.web.context.ContextLoader|Context initialization failed|#]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDataService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.acme.data.repositories.UserRepository com.acme.data.services.UserDataService.userRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: No [ManagedType] was found for the key class [com.acme.domain.entities.User] in the Metamodel - please verify that the [Managed] class was referenced in persistence.xml using a specific <class>com.acme.domain.entities.User</class> property or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element.
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4779)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:897)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:873)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:958)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1599)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.acme.data.repositories.UserRepository com.acme.data.services.UserDataService.userRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: No [ManagedType] was found for the key class [com.acme.domain.entities.User] in the Metamodel - please verify that the [Managed] class was referenced in persistence.xml using a specific <class>com.acme.domain.entities.User</class> property or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element.
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:512)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 27 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: No [ManagedType] was found for the key class [com.acme.domain.entities.User] in the Metamodel - please verify that the [Managed] class was referenced in persistence.xml using a specific <class>com.acme.domain.entities.User</class> property or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element.
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:149)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:102)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1442)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:305)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:876)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:818)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:735)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:484)
... 29 more
Caused by: java.lang.IllegalArgumentException: No [ManagedType] was found for the key class [com.acme.domain.entities.User] in the Metamodel - please verify that the [Managed] class was referenced in persistence.xml using a specific <class>com.acme.domain.entities.User</class> property or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element.
at org.eclipse.persistence.internal.jpa.metamodel.MetamodelImpl.entityEmbeddableManagedTypeNotFound(MetamodelImpl.java:174)
at org.eclipse.persistence.internal.jpa.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:489)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:58)
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:65)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:149)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:87)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:70)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:137)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:125)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:41)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:142)
... 37 more
I was able to solve my issue but it was another setup as the one above, i just add a few things i stumbled across until i was able to solve it in my SE-Environment:
Bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=338837 affects EclipseLink Version 2.2.0 and below versions. Mostly happening in Local-Environment (RESOURCE_LOCAL). A EclipseLink version-Upgrade or the following workaround may help:
<exclude-unlisted-classes>false</exclude-unlisted-classes>
Having multiple persistence.xml files in classpath (e.g. especially in 3th party JARs) that all define the same persistence-unit-name (above "default" may be very common). Try renaming your persistence-unit-name in this case as a first step
In case of renaming the persistence-unit-name worked but changing it back to the old value reproduces the problem there is either above mentioned 3th party JAR or old JARs of your own project beeing included to your build (e.g. refactoring/ renaming on project level or similar changed the structure so for example a maven build could still take old build artifacts from the repository)
Finaly when it comes to my setup (Spring-Standalone Application, no persistence.xml but tons of Spring-configurations because a custom company Framework is used) it showed that i just forgot to add the the entity-package of the custom framework-core when i wanted to run one of their service-implementations (Spring-Bean implementation) in my local project rather than having their service-implementation from a JAR-dependency. So make sure that you have all of the required entity packages listed for your EntityManagerFactory:
<bean id="customEntityManagerFactory" parent="abstractEntityManagerFactory">
<property name="dataSource" ref="dataSource"/>
<!-- Packages of EntityClasses -->
<property name="packagesToScan">
<list merge="true">
<value>ch.company.div1.foo.bar.model</value>
<value>ch.company.div1.foo.barnicle.model</value>
<value>ch.company.div2.we.help.model</value>
</list>
</property>
<property name="jpaProperties">
<props merge="true">
<prop key="eclipselink.target-database">org.eclipse.persistence.platform.database.SQLServerPlatform
</prop>
<prop key="javax.persistence.transactionType">RESOURCE_LOCAL</prop>
</props>
</property>
</bean>
In my case i forgot to add the model packagege with the used entitys of another division (that writes the custom framework core) of our company.
Good luck, that error's a beast :/
Not sure if you are having the same problem I had: trying to create 2 different entity factories... The exception is the same, so maybe this will help. Essentially this exception was happening when it was instantiating an Entity on the wrong EntityManagerFactory.
My project was running fine with a single database connection but when I added a second one EclipseLink was confused on where to instantiate my entities. After a few debug my conclusion was to remove the property "packagesToScan" from my root-context.xml and replace it with a "persistenceXmlLocation". In that XML, I listed every class I needed to be scanned and excluded everything else with "<exclude-unlisted-classes>"
Here is my full XML configuration that is currently working:
root-context.xml
<bean id="dataSource1" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://server1.example.com:5432/db1" />
<property name="username" value="username" />
<property name="password" value="password" />
<property name="defaultAutoCommit" value="false" />
<property name="initialSize" value="5" />
<property name="maxIdle" value="5" />
<property name="validationQuery" value="SELECT 1" />
<property name="timeBetweenEvictionRunsMillis" value="600000" />
<property name="poolPreparedStatements" value="true" />
<property name="maxOpenPreparedStatements" value="10" />
</bean>
<bean id="dataSource2" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://server2.example.com:5432/db2" />
<property name="username" value="user" />
<property name="password" value="password" />
<property name="defaultAutoCommit" value="false" />
<property name="initialSize" value="5" />
<property name="maxIdle" value="5" />
<property name="validationQuery" value="SELECT 1" />
<property name="timeBetweenEvictionRunsMillis" value="600000" />
<property name="poolPreparedStatements" value="true" />
<property name="maxOpenPreparedStatements" value="10" />
</bean>
<bean id="emf1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource1" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence1.xml" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="showSql" value="false" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="eclipselink.weaving" value="false" />
<entry key="eclipselink.logging.level" value="WARNING" />
<entry key="eclipselink.logging.timestamp" value="false" />
<entry key="eclipselink.logging.session" value="false" />
<entry key="eclipselink.logging.thread" value="false" />
</map>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean id="emf2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource2" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence2.xml" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="showSql" value="false" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="eclipselink.weaving" value="false" />
<entry key="eclipselink.logging.level" value="WARNING" />
<entry key="eclipselink.logging.timestamp" value="false" />
<entry key="eclipselink.logging.session" value="false" />
<entry key="eclipselink.logging.thread" value="false" />
</map>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean name="transaction1" class="org.springframework.orm.jpa.JpaTransactionManager" p:entity-manager-factory-ref="emf1" />
<bean name="transaction2" class="org.springframework.orm.jpa.JpaTransactionManager" p:entity-manager-factory-ref="emf2" />
<jpa:repositories base-package="org.myproject.repository1" transaction-manager-ref="transaction1" entity-manager-factory-ref="emf1" />
<jpa:repositories base-package="org.myproject.repository2" transaction-manager-ref="transaction2" entity-manager-factory-ref="emf2" />
<tx:annotation-driven />
persistence1.xml
<persistence-unit name="persistence1" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.myproject.repository1.Repo1</class>
<class>org.myproject.repository1.Repo2</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
persistence2.xml
<persistence-unit name="persistence2" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.myproject.repository2.Repo1</class>
<class>org.myproject.repository2.Repo2</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
So, this works for me...
Apparently specifying each "persistence.xml" location prevents classes that are meant for another EntityManagerFactory to be instantiated on the first "emf". In fact, this looks like a bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=338837. All I could figure out from my debugging is that without the "persistenceXmlLocation" ALL classes that are found with "packageScan" were instantiated on the first created "emf", the second "emf" was completely ignored.
Hope this helps. Good luck!
Add the package (com.acme.domain.entities) with entities to packagesToScan.
Set the PersistenceUnitName, instead of the persistenceXmlLocation
No persistence.xml needed.
factory.setPersistenceUnitName("dummy1");
factory.setPersistenceUnitName("dummy2");

Cannot port WAR file from Tomcat to Glassfish. Error with RESOURCE_LOCAL versus JTA

I'm trying to take a WAR, which deploys and runs fine on Tomcat, and deploy it on Glassfish. The initial error message in Glassfish is:
com.sun.enterprise.deployment.backend.IASDeploymentException:
Deployment Error -- The
persistence-context-ref-name
[org.nhindirect.config.store.dao.impl.AnchorDaoImpl/entityManager]
in module
[C:\Sun\AppServer\domains\domain1\applications\j2ee-modules\config-service]
resolves to a persistence unit called
[config-store] which is of type
RESOURCE_LOCAL. Only persistence units
with transaction type JTA can be used
as a container managed entity manager.
Please verify your application.
The WAR does not have a persistence.xml in its META-INF folder. However, there is a JAR under WEB-INF\lib that itself contains a persistence.xml. The following are its contents:
<?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_1_0.xsd"
version="1.0">
<persistence-unit name="config-store" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.hbm2ddl.auto" value="validate" />
</properties>
</persistence-unit>
</persistence>
So here's my question: is it possible to run a WAR configured for RESOURCE_LOCAL on Glassfish, or must I reconfigure the WAR for JTA?
I've investigated the first option by making the following changes to the WAR's web.xml:
Changed version="2.5" to version="2.4"
Changed xmlns="http://java.sun.com/xml/ns/javaee"
to
xmlns="http://java.sun.com/xml/ns/j2ee"
Changed xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
to
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
After these changes, the WAR seemed to deploy successfully, however, I could not access its WSDL and the following error was found in the Glassfish log:
Exception sending context initialized
event to listener instance of class
org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name
'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0'
defined in ServletContext resource
[/WEB-INF/beans.xml]: Initialization
of bean failed; nested exception is
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name
'entityManagerFactory' defined in
ServletContext resource
[/WEB-INF/beans.xml]: Invocation of
init method failed; nested exception
is java.lang.NoClassDefFoundError:
javassist/bytecode/ClassFile at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at
java.security.AccessController.doPrivileged(Native
Method) at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:880)
at
org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:596)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:365)
at
org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4655)
at
org.apache.catalina.core.StandardContext.start(StandardContext.java:5364)
at
com.sun.enterprise.web.WebModule.start(WebModule.java:345)
at
org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:986)
at
org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:970)
at
org.apache.catalina.core.StandardHost.addChild(StandardHost.java:704)
at
com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1649)
at
com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1254)
at
com.sun.enterprise.server.WebModuleDeployEventListener.moduleDeployed(WebModuleDeployEventListener.java:182)
at
com.sun.enterprise.server.WebModuleDeployEventListener.moduleDeployed(WebModuleDeployEventListener.java:278)
at
com.sun.enterprise.admin.event.AdminEventMulticaster.invokeModuleDeployEventListener(AdminEventMulticaster.java:1005)
at
com.sun.enterprise.admin.event.AdminEventMulticaster.handleModuleDeployEvent(AdminEventMulticaster.java:992)
at
com.sun.enterprise.admin.event.AdminEventMulticaster.processEvent(AdminEventMulticaster.java:470)
at
com.sun.enterprise.admin.event.AdminEventMulticaster.multicastEvent(AdminEventMulticaster.java:182)
at
com.sun.enterprise.admin.server.core.DeploymentNotificationHelper.multicastEvent(DeploymentNotificationHelper.java:308)
at
com.sun.enterprise.deployment.phasing.DeploymentServiceUtils.multicastEvent(DeploymentServiceUtils.java:231)
at
com.sun.enterprise.deployment.phasing.ServerDeploymentTarget.sendStartEvent(ServerDeploymentTarget.java:298)
at
com.sun.enterprise.deployment.phasing.ApplicationStartPhase.runPhase(ApplicationStartPhase.java:132)
at
com.sun.enterprise.deployment.phasing.DeploymentPhase.executePhase(DeploymentPhase.java:108)
at
com.sun.enterprise.deployment.phasing.PEDeploymentService.executePhases(PEDeploymentService.java:966)
at
com.sun.enterprise.deployment.phasing.PEDeploymentService.start(PEDeploymentService.java:609)
at
com.sun.enterprise.deployment.phasing.PEDeploymentService.start(PEDeploymentService.java:653)
at
com.sun.enterprise.admin.mbeans.ApplicationsConfigMBean.start(ApplicationsConfigMBean.java:773)
at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at
java.lang.reflect.Method.invoke(Method.java:597)
at
com.sun.enterprise.admin.MBeanHelper.invokeOperationInBean(MBeanHelper.java:390)
at
com.sun.enterprise.admin.MBeanHelper.invokeOperationInBean(MBeanHelper.java:373)
at
com.sun.enterprise.admin.config.BaseConfigMBean.invoke(BaseConfigMBean.java:477)
at
com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:836)
at
com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:761)
at
sun.reflect.GeneratedMethodAccessor13.invoke(Unknown
Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at
java.lang.reflect.Method.invoke(Method.java:597)
at
com.sun.enterprise.admin.util.proxy.ProxyClass.invoke(ProxyClass.java:90)
at $Proxy1.invoke(Unknown Source) at
com.sun.enterprise.admin.server.core.jmx.SunoneInterceptor.invoke(SunoneInterceptor.java:304)
at
com.sun.enterprise.interceptor.DynamicInterceptor.invoke(DynamicInterceptor.java:170)
at
com.sun.enterprise.deployment.client.DeploymentClientUtils.startApplication(DeploymentClientUtils.java:159)
at
com.sun.enterprise.deployment.client.DeployAction.run(DeployAction.java:538)
at
java.lang.Thread.run(Thread.java:619)
Caused by:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name
'entityManagerFactory' defined in
ServletContext resource
[/WEB-INF/beans.xml]: Invocation of
init method failed; nested exception
is java.lang.NoClassDefFoundError:
javassist/bytecode/ClassFile at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at
java.security.AccessController.doPrivileged(Native
Method) at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:308)
at
org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:270)
at
org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.detectPersistenceExceptionTranslators(PersistenceExceptionTranslationInterceptor.java:122)
at
org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.(PersistenceExceptionTranslationInterceptor.java:78)
at
org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisor.(PersistenceExceptionTranslationAdvisor.java:70)
at
org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:97)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1326)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
... 56 more Caused by:
java.lang.NoClassDefFoundError:
javassist/bytecode/ClassFile at
org.hibernate.ejb.packaging.AbstractJarVisitor.checkAnnotationMatching(AbstractJarVisitor.java:236)
at
org.hibernate.ejb.packaging.AbstractJarVisitor.executeJavaElementFilter(AbstractJarVisitor.java:202)
at
org.hibernate.ejb.packaging.AbstractJarVisitor.addElement(AbstractJarVisitor.java:163)
at
org.hibernate.ejb.packaging.FileZippedJarVisitor.doProcessElements(FileZippedJarVisitor.java:100)
at
org.hibernate.ejb.packaging.AbstractJarVisitor.getMatchingEntries(AbstractJarVisitor.java:139)
at
org.hibernate.ejb.Ejb3Configuration.addScannedEntries(Ejb3Configuration.java:287)
at
org.hibernate.ejb.Ejb3Configuration.scanForClasses(Ejb3Configuration.java:614)
at
org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:360)
at
org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:131)
at
org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:224)
at
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:291)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335)
... 73 more
Part of the above error message complains about javassist. This seems strange because the following section is in the WAR's pom.xml
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
If helpful, here are the contents of the WAR's beans.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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jaxws="http://cxf.apache.org/jaxws"
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-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"
default-autowire="byName">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<context:annotation-config />
<context:component-scan base-package="org.nhindirect.config" />
<tx:annotation-driven transaction-manager="transactionManager" />
<jaxws:endpoint id="configurationService"
address="/ConfigurationService" >
<jaxws:implementor>
<bean id="configurationServiceImpl"
class="org.nhindirect.config.service.impl.ConfigurationServiceImpl">
<property name="domainSvc" ref="domainSvc"/>
<property name="addressSvc" ref="addressSvc"/>
<property name="anchorSvc" ref="anchorSvc"/>
<property name="certSvc" ref="certSvc"/>
<property name="settingSvc" ref="settingSvc"/>
<property name="DNSSvc" ref="dnsSvc"/>
</bean>
</jaxws:implementor>
</jaxws:endpoint>
<!-- <jaxws:endpoint id="addressService" implementor="org.nhindirect.config.service.ws.AddressServiceWS"
address="/AddressService" /> -->
<!-- Service Implementations -->
<bean id="domainSvc" class="org.nhindirect.config.service.impl.DomainServiceImpl">
<property name="dao" ref="domainDao"/>
</bean>
<bean id="addressSvc" class="org.nhindirect.config.service.impl.AddressServiceImpl">
<property name="dao" ref="addressDao"/>
</bean>
<bean id="anchorSvc" class="org.nhindirect.config.service.impl.AnchorServiceImpl">
<property name="dao" ref="anchorDao"/>
</bean>
<bean id="certSvc" class="org.nhindirect.config.service.impl.CertificateServiceImpl">
<property name="dao" ref="certificateDao"/>
</bean>
<bean id="settingSvc" class="org.nhindirect.config.service.impl.SettingServiceImpl">
<property name="dao" ref="settingDao"/>
</bean>
<bean id="dnsSvc" class="org.nhindirect.config.service.impl.DNSServiceImpl">
<property name="dao" ref="dnsDao"/>
</bean>
<!-- DAO's -->
<bean id="domainDao" class="org.nhindirect.config.store.dao.impl.DomainDaoImpl"/>
<bean id="addressDao" class="org.nhindirect.config.store.dao.impl.AddressDaoImpl"/>
<bean id="anchorDao" class="org.nhindirect.config.store.dao.impl.AnchorDaoImpl" />
<bean id="certificateDao" class="org.nhindirect.config.store.dao.impl.CertificateDaoImpl"/>
<bean id="settingDao" class="org.nhindirect.config.store.dao.impl.SettingDaoImpl"/>
<bean id="dnsDao" class="org.nhindirect.config.store.dao.impl.DNSDaoImpl"/>
<!-- Exception translation bean post processor -->
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<!-- SWAP THIS JPA IMPLEMENTATION WITH THE APPROPROATE DB CONFIGURATION
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter">
<bean 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>
</property>
<property name="persistenceUnitName" value="config-store" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql:nhindconfig" />
<property name="username" value="nhind" />
<property name="password" value="nhind" />
</bean>
-->
<!-- EMBEDDED DERBY JPA CONFIGURATION FOR A WORKING OUT OF THE BOX CONFIGURATION WITH NO PREREQUISITES OF
SETTING UP AN EXTERNAL DATABASE. REMOVE THIS SECTION AND REPLACE WITH READ JPA CONFIGURATION (SEE
ABOVE SECTION) FOR PRODUCTION -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter">
<bean 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" /> -->
<property name="databasePlatform" value="org.hibernate.dialect.DerbyDialect" />
</bean>
</property>
<property name="dataSource" ref="dataSource"/>
<property name="persistenceUnitName" value="config-store" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="url" value="jdbc:derby:nhindconfig;create=true" />
<property name="username" value="nhind" />
<property name="password" value="nhind" />
</bean>
<!-- END DERBY JPA CONFIGURATION -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" />
</beans>
Sorry if I've provided too much information. I'm new to JPA and wasn't sure what would and wouldn't be helpful to anyone.
Thank you in advance.
Somewhere in your code you're probably injecting an EntityManager using code that looks something like this:
#PersistanceContext // Requires JTA
EntityManager em;
In this situation, you're asking the container (Glassfish itself, to create and manage the EntityManager for you. Glassfish being clusterable, attempts to protect you from accidentally making a transaction across multiple servers that is not truly ACID, but requiring you to use a JTA-transaction (which is sharable between multiple clustered servers).
If you know for sure you are NEVER going to cluster your glassfish container for this application, you can safely keep using RESOURCE_LOCAL transactions, however, you cannot have Glassfish manage that EntityManager for you. You can have Glassfish manage an EntityManagerFactory though.
#PersistanceUnit // Does NOT require JTA
EntityManagerFactory factory;
This is safe to use for persistance units that are RESOURCE_LOCAL. You just need to request an EntityManager from the factory using factory.createEntityManager().
Now your EntityManager is application-managed, not container-managed. So Glassfish will assume that you will handle transaction isolation in a cluster.