jboss5.1+spring+jpa [ No unique bean of type [javax.persistence.EntityManagerFactory] is defined] - spring

Define oracle-ds.xml
<local-tx-datasource>
<jndi-name>timekerOracleDS</jndi-name>
....
</local-tx-datasource>
Define persistence.xml
<persistence-unit name="timeker" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:timekerOracleDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="jboss.entity.manager.factory.jndi.name" value="java:/timeker"/>
</properties>
</persistence-unit>
Define spring applicationContext.xml
<aop:aspectj-autoproxy />
<context:annotation-config />
<context:component-scan base-package="com.paokuang"/>
<jee:jndi-lookup id="entityManagerFactory" jndi-name="java:/timeker"/>
<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManagerName" value="java:/TransactionManager"/>
<property name="userTransactionName" value="UserTransaction"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
Define the Spring configuration file in the web.xml file
<persistence-unit-ref>
<persistence-unit-ref-name>persistence/timeker</persistence-unit-ref-name>
<persistence-unit-name>timeker</persistence-unit-name>
</persistence-unit-ref>
but when I deployed the war into jboss,occured the error:
Error creating bean with name 'productTypeServiceBean': Injection of persistence fields failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0
How to resolve the problem or tell the right configuration spring+jpa+jboss?

You are missing the EntityManagerFactory bean in your applicationContext.xml.
Probably the easiest way is to configure the LocalContainerEntityManagerFactoryBean:
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="someDataSource"/>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
</bean>
See http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html for more details.

Related

ignoreUnresolvablePlaceholders not working

I am using ignoreUnresolvablePlaceholders in my spring context.
as below.
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:messaging.properties</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="false" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>
event setting ignoreUnresolvablePlaceholders to true its not ignoring my spring bean being injecting.
i am passing amq.topic= in property file for
<bean id="messageTopic1" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="${amq.topic}" />
</bean>
But its not ignoring this bean for being injecting.
below is my Spring-context.xml amd property file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
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.1.xsd">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:messaging.properties</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="false" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>
<!-- Active MQ Broker Configuration Details -->
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="${amq.url}" />
</bean>
<bean id="messageQueue1" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="${amq.queue}" />
</bean>
<bean id="messageTopic1" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="${amq.topic}" />
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
<bean id="activeMQ" class="com.isc.common.messaging.AmqUtilityHelper">
<property name="destination" ref="messageQueue1" />
<property name="jmsTemplate" ref="jmsTemplate" />
</bean>
<!-- <bean id="activeMQ1" class="com.isc.common.messaging.AmqUtilityHelper">
<property name="destination" ref="messageTopic1" />
<property name="jmsTemplate" ref="jmsTemplate" />
</bean> -->
<bean id="messageBroker" class="com.isc.common.messaging.AmqUtilityHelper">
<property name="activeBroker" value="${active.broker}" />
</bean>
</beans>
And Below is the property file that i am loading.
#AMQ/Solace properties production:
# uncomment the borker to use
active.broker=activeMQ
#active.broker=solace
#active.broker=activeMQ
#AMQ Broker Properties
amq.url=failover:(tcp://localhost:61616)??initialReconnectDelay=2000&maxReconnectAttempts=5
amq.queue=messageQueue1
amq.topic=
#Solace Broker Properties
solace.url=smf://192.168.56.101:55555
solace.userName=spring_user#Solace_Spring_VPN
solace.passWord=spring_password
solace.jndiName=JNDI/CF/spring1
solace.queue=JNDI/Q/requests
#solace.topic=JNDI/topic1
By default, ApplicationContext implementations eagerly create and
configure all singleton beans as part of the initialization process.
Generally, this pre-instantiation is desirable, because errors in the
configuration or surrounding environment are discovered immediately,
as opposed to hours or even days later. When this behavior is not
desirable, you can prevent pre-instantiation of a singleton bean by
marking the bean definition as lazy-initialized. A lazy-initialized
bean tells the IoC container to create a bean instance when it is
first requested, rather than at startup.
Can you please try to lazily initialize your bean using below construct.
lazy-init="true"
<bean id="messageTopic1" class="org.apache.activemq.command.ActiveMQTopic"
lazy-init="true">
<constructor-arg value="${amq.topic}" />
</bean>

Spring 4 Jpa Hibernate - Can't Inject EntityManager

I guess I have the same problem as many people, but unsolved on most of cases. I will try anyway, hope you guys can help me.
The problem is in my repository when I try to inject que Entity Manager using #persistenceContext annotation and always comes null.
The stack:
Spring 4.2.5
Spring Data 1.10.1
Hibernate 5
This is my xml for Sprint data:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="conquerPU"/>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="packagesToScan" value="com.conquer.module" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL82Dialect</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/conquer" />
<property name="username" value="app" />
<property name="password" value="10203040" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<jpa:repositories base-package="com.conquer.module" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/>
This is my application context.xml
<context:annotation-config/>
<context:component-scan base-package="com">
<context:include-filter type="aspectj" expression="com.*" />
</context:component-scan>
<!-- a HTTP Session-scoped bean exposed as a proxy -->
<bean id="sessionData" class="com.conquer.common.SessionData" scope="session">
<aop:scoped-proxy/>
</bean>
<!--Hibernate persistence interceptor - Used for audit data-->
<bean id="hibernateInterceptor" class="com.conquer.module.security.interceptor.HibernateInterceptor"></bean>
<!--Application Context to be used anywhere-->
<bean id="applicationContextProvder" class="com.conquer.common.ApplicationContextProvider"/>
<!-- SpringMVC -->
<import resource="spring-mvc.xml"/>
<!-- SpringData -->
<import resource="spring-jpa.xml"/>
<!-- SpringSecurity -->
<import resource="spring-security.xml"/>
This is my repository
#Repository
#Transactional
public class BaseRepositoryImpl<T, ID extends Serializable> implements BaseRepository<T, ID> {
#PersistenceContext
public EntityManager em;
public RepositoryFactorySupport baseFactory;
public BaseRepository<T, ID> baseRepository;
public BaseRepositoryImpl() {
System.out.println("BASE REPOSITORY RUNNING...");
this.baseFactory = new JpaRepositoryFactory(em);
this.baseRepository = this.baseFactory.getRepository(BaseRepository.class);
}
// Implementations here ...
}
This is my 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="conquerPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect"/>
<property name = "hibernate.show_sql" value = "true" />
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.ejb.interceptor" value="com.conquer.module.security.interceptor.HibernateInterceptor"/>
</properties>
</persistence-unit>
</persistence>
Although this question is quite old, we faced with this problem as well and solved it by adding this bean to our application context:
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
The documentation for context:annotation-config clearly states that this should not be necessary, but in our case it was (albeit we use Spring 4.2 inside Eclipse Virgo 3.7 with Gemini Blueprint, so this setup is probably far from mainstream).

Conversion exception with Hibernate 4 while JUnit testing with Spring

I created the sessionFactory bean with an org.springframework.orm.hibernate4.LocalSessionFactoryBean class and the transactionManager bean with an org.springframework.orm.hibernate4.HibernateTransactionManager class.
On performing the JUnits tests the following shows up.
" Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'org.hibernate.SessionFactory' for property 'sessionFactory'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.hibernate.SessionFactory] for property 'sessionFactory': no matching editors or conversion strategy found".
The Hibernate Core dependency version is 4.3.9 .
Please advice.
Below is my datasource.xml for the JUnit tests. The tests run under the dev profile. While the exact .xml code runs under the production profile for the main app smoothly.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<context:component-scan base-package="com.caveofprogramming.spring.test">
</context:component-scan>
enter code here
<beans profile="dev">`enter code here`
<context:property-placeholder
location="com/caveofprogramming/spring/web/test/config/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="username" value="${jdbc.username}"></property>
</bean>
<!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="javax.persistence.validation.group.pre-persist">
com.caveofprogramming.spring.web.dao.PersistenceValidationGroup
</prop>
<prop key="javax.persistence.validation.group.pre-update">
com.caveofprogramming.spring.web.dao.PersistenceValidationGroup
</prop>
<prop key="javax.persistence.validation.group.pre-remove">
com.caveofprogramming.spring.web.dao.PersistenceValidationGroup
</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.caveofprogramming.spring.web.dao</value>
</list>
</property>
</bean>
<!-- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource"></property>
<property name="sessionFactory" value="sessionFactory"></property>
</bean>
<tx:annotation-driven />
<bean id="exceptionTranslator"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor">
</bean>
</beans>
</beans>
You must pass reference to the bean, not value. So change this:
<property name="sessionFactory" value="sessionFactory"></property>
to
<property name="sessionFactory" ref="sessionFactory"></property>

Setting up Spring JTA transaction in Jboss 7.1.1

Hello I am trying to setup spring JTA in myEclipse for Spring.Below are my configuration files:
applicationContent.xml where i have added two imports(note it do include schema locations)
<import resource="infrastructure.xml"/>
<import resource="classpath:**/persistence.xml"/>
infrastrutre.xml(unable to add schema due to input validations)
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jtaDataSource" ref="masterDataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>
<!-- <bean id="masterDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:/test_JTA"></property>
</bean> -->
<jee:jndi-lookup id="masterDataSource" jndi-name="java:/Test_JTA" />
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- <property name="databasePlatform"
value="org.hibernate.dialect.MySQL5InnoDBDialect" /> -->
<property name="database" value="MYSQL" />
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
</bean>
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="mainPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.abc.PaymentCard</class>
<jar-file>mysql-connector-java-5.1.23-bin.jar</jar-file>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/>
<property key="hibernate.transaction.factory_class">org.hibernate.transaction.CMTTransactionFactory</property>
<property key="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.JBossTransactionManagerLookup</property>
</properties>
</persistence-unit>
</persistence>
I am getting error
JBAS010402: Unable to instantiate driver class "com.mysql.jdbc.Driver": org.jboss.msc.service.DuplicateServiceException: Service jboss.jdbc-driver.JTA_Test_war is already registered
I goggled this error but still haven't got any satisfactory answers.Kindly help
I am not sure about JBoss but for Glassfish there is an Ext directory for the Jars you want in the Classpath. So try to figure out how to deploy mysql-connector-java*.jar to your domain.
i know its late but, i believe i fixed this error by using a different factory class.
<property name="hibernate.transaction.factory_class" value="org.hibernate.ejb.transaction.JoinableCMTTransactionFactory"/>
hope it helps :)

Spring JPA/Hibernate in standalone app

I am utilizing spring in non web application and I am using hibernate for working with DB. Problem I am experiencing is that while "registerShutdownHook();" does close spring context container it does not properly shut down and close resources for JPA so my connections to DB are getting maxed out.
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="pu" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="false" />
<property name="showSql" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
I use configuration presented above to fire up JPA layer and use "#Transactional" annotations to inject EM's into DAO's.
Maybe someone could help me out what am I missing or how should I handle proper closing of JPA sessions in standalone environment ?
Thank you,
P.S. Exception I am getting is: java.net.SocketException: No buffer space available (maximum connections reached?): connect
1.Create transaction manager as follow :
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="persistenceUnitName" value="persistanceUnit"/>
<property name="dataSource" ref="dataSource"/>
<property name="persistenceXmlLocation" value="classpath:persistence.xml"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${db.orm.showsql}" />
<property name="generateDdl" value="${db.orm.generateDdl}" />
<property name="database" value="${db.type}"/>
<property name="databasePlatform" value="${db.orm.dialect}" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
2.use persistance.xml(should be in classpath)
<?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="persistanceUnit" transaction-type="RESOURCE_LOCAL">
<description>Oracle db Persistence Unit</description>
<class>com.company.YourModelClass</class>
<properties/>
</persistence-unit>
</persistence>
3.Add following annotation in applicationContext.xml
<context:component-scan base-package="com.yourcompany.basepackage" />
4.annoatate your Entitymanager in service class like:
#PersistenceContext
private EntityManager em = null;
5.Inject TrasnsactionManager to :
private PlatformTransactionManager platformTransactionManager = null;
6.persist object like:
platformTransactionManager .persist(obj);
This is another example of application Context.xml with JPA. It works fine for me.
<context:property-placeholder location=”classpath:jdbc.properties”/>
<!– Connection Pool –>
<bean id=”dataSource” destroy-method=”close”>
<property name=”driverClass” value=”${jdbc.driverClass}”/>
<property name=”jdbcUrl” value=”${jdbc.url}”/>
<property name=”user” value=”${jdbc.username}”/>
<property name=”password” value=”${jdbc.password}”/>
</bean>
<!– JPA EntityManagerFactory –>
<bean id=”entityManagerFactory”
p:dataSource-ref=”dataSource”>
<property name=”jpaVendorAdapter”>
<bean>
<property name=”database” value=”${jdbc.database}”/>
<property name=”showSql” value=”${jdbc.showSql}”/>
</bean>
</property>
</bean>
<!– Transaction manager for a single JPA EntityManagerFactory (alternative to JTA) –>
<bean id=”transactionManager”
p:entityManagerFactory-ref=”entityManagerFactory”/>
<!– Activates various annotations to be detected in bean classes for eg #Autowired–>
<context:annotation-config/>
<!– enable the configuration of transactional behavior based on annotations –>
<tx:annotation-driven transaction-manager=”transactionManager”/>
<!– Property Configurator –>
<bean id=”propertyConfigurer”>
<property name=”location” value=”jdbc.properties”/>
</bean>
<context:component-scan base-package=”com.test.dao”/>
</beans>

Resources