No Persistance provider for EntityManager - using Hibernate and Spring MVC - spring

I have Spring MVC project. I am using HSQL database and Hibernate. I have got stuck during making connection with Spring MVC (JPA as default) and Hibernate.
I have created persistance.xml file in Spring MVC directory: src/main/resources/META-INF. I have also tried to place it in Spring MVC directory: Deployed Resources/webapp/WEB-INF/classes/META-INF. I don't know which one is correct. I have still the same problem.
This is my persistance.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
<persistence-unit name="entityManager">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>package.pl.models.Users</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:file:/home/user/hsqldb/lib/my.spring.mvc/mybase" />
<property name="javax.persistence.jdbc.user" value="user" />
<property name="javax.persistence.jdbc.password" value="password" />
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider" />
</properties>
</persistence-unit>
This is one of my Spring MVC controller method body:
UsersHome usersHome = new UsersHome();
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("entityManager");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
usersHome.setEntityManager(entityManager);
Users user = usersHome.findByUsername(login);
I have received error on the line when I have used EntityManagerFactory for the first time - indicating the name of my Persistence Unit.
My exception is:
org.springframework.web.util.NestedServletException: Request processing failed;
nested exception is javax.persistence.PersistenceException: No Persistence
provider for EntityManager named entityManager
And the root cause is:
javax.persistence.PersistenceException: No Persistence provider for EntityManager named entityManager
I have used appropriate name in EntityManagerFactory. Presumably I have done mistake in my Dispatcher Servlet Context file. I have this code according to Hibernate etc.:
<!-- Hibernate session factory -->
<beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource">
<beans:ref bean="dataSource" />
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop>
</beans:props>
</beans:property>
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>package.pl.models.Users</beans:value>
</beans:list>
</beans:property>
</beans:bean>
<!-- Hibernate session factory end -->
<!-- <beans:bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<beans:property name="persistenceUnitName" value="entityManager" />
</beans:bean> -->
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="sessionFactory" />
</beans:bean>
<!-- <beans:bean id="usersDao" class="hutter.pl.dao.UsersHome">
<beans:property name="entityManagerFactory" ref="entityManagerFactory" />
</beans:bean> -->
I have commented the bean id="entityManagerFactory" and bean id="usersDao". Are the necessary? However I can't start my web application with uncommented bean id="entityManagerFactory". I am receiving this exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with
name 'entityManagerFactory' defined in ServletContext resource
[/WEB-INF/spring/appServlet/servlet-context.xml]: Invocation of init method failed;
nested exception is javax.persistence.PersistenceException: No Persistence
provider for EntityManager named entityManager

Sorry, I have not read your full question. I stopped when I saw this: persistance.xml. What about using persistence.xml?

Put your xml file into WEB-INF folder. The xml file contents sessionFactory and all that stub.
And import it into spring.xml file as follows:
<import resource="classpath:persistance.xml" />

Related

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).

Spring data 1.6.0 GA cannot find entity manager factory bean by custom id

I have found the strange behavior of Spring data 1.6.0 (downgraded version 1.5.2 does not have this problem). It seems that this version strictly demands the id of entity manager factory bean to be "entityManagerFactory". If not, this error appears when running TestNG test:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMapppingContext': Cannot create inner bean '(inner bean)#36b87404' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#36b87404': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined
My configuration is:
<!-- ************************************************************** -->
<!-- Database configuration -->
<!-- ************************************************************** -->
<!-- Entity manager factory bean -->
<bean id="entityManagerFactoryCustomId"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="test-system" />
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<array>
<value>${pds.db.scan.model}</value>
</array>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">${jdbc.showsql}</prop>
<prop key="hibernate.format_sql">${jdb.formatsql}</prop>
<prop key="hibernate.hbm2ddl.auto">${jdbc.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<!-- C3P0 connection pool -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<!-- Connection properties -->
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- Pool properties -->
<property name="minPoolSize" value="${pool.minsize}" />
<property name="maxPoolSize" value="${pool.maxsize}" />
<property name="initialPoolSize" value="${pool.initialPoolSize}" />
<property name="maxStatements" value="${pool.maxstatements}" />
<property name="acquireIncrement" value="${pool.acquireincrement}" />
<property name="preferredTestQuery" value="${jdbc.check}" />
<property name="numHelperThreads" value="${pool.threads}" />
</bean>
<!-- JPA transaction manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryCustomId" />
</bean>
<!-- Activate Spring Data JPA repository support -->
<jpa:repositories base-package="pds.archiva.db.repository" />
</code>
Is it a bug in Spring Data JPA or am I doing something wrong ? Tested on windows java 64bit 7u55 with following versions:
spring.framework.version = 4.0.5.RELEASE
spring.security.version = 3.2.4.RELEASE
spring.data-jpa.version = 1.6.0.RELEASE
As I have written, the same test works with only changing spring.data-jpa.version = 1.5.2.RELEASE ... or change id of bean to "entityManagerFactory" instead of "entityManagerFactoryCustomId".
Just added #StéphaneNicoll answer:
set the entity manager explicitly then (see entity-manager-factory-refelement in jpa:repositories . Looks like the documentation might be outdated.

Issue with JMS + AOP + JNDI Resources

Hi and happy new year
I'm working on a project which need to implement jms, aop and some jndi resources.
So far, the project works fine when there are only jms and jndi but when i activated aop, i had some troubles.. here is the configuration :
<!-- JMS implementation -->
<bean id="jmsRefConnectionFactory.activemq" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jms/activeMQConnectionFactory" />
<property name="lookupOnStartup" value="false" />
<property name="proxyInterface" value="javax.jms.QueueConnectionFactory" />
</bean>
<bean id="jmsRefQueue.activemq" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jms/activeMQQueue" />
<property name="lookupOnStartup" value="false" />
<property name="proxyInterface" value="javax.jms.Queue" />
</bean>
<bean id="jmsConnectionFactory.activemq" class="org.springframework.jms.connection.SingleConnectionFactory">
<constructor-arg ref="jmsRefConnectionFactory.activemq" />
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="jmsConnectionFactory.activemq" />
<property name="defaultDestination" ref="jmsRefQueue.activemq" />
<property name="destinationResolver" ref="jmsDestinationResolver.amq" />
<property name="sessionTransacted" value="true" />
<property name="sessionAcknowledgeMode" value="#{T(javax.jms.Session).CLIENT_ACKNOWLEDGE}" />
</bean>
<bean id="transactionManager" class="org.springframework.jms.connection.JmsTransactionManager">
<property name="connectionFactory" ref="jmsRefConnectionFactory.activemq" />
</bean>
<bean id="jmsDestinationResolver.amq"
class="org.springframework.jms.support.destination.DynamicDestinationResolver" />
When I start the application, I get this error :
Caused by: org.springframework.aop.AopInvocationException: AOP configuration seems to be invalid: tried calling method [public abstract javax.jms.Connection javax.jms.ConnectionFactory.createConnection() throws javax.jms.JMSException] on target [org.apache.activemq.ActiveMQConnectionFactory#239f 6]; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class
Context.xml content :
<!-- APACHE MQ -->
<Resource name="jms/activeMQConnectionFactory" auth="Container"
type="org.apache.activemq.ActiveMQConnectionFactory" description="JMS Connection Factory"
factory="org.apache.activemq.jndi.JNDIReferenceFactory" HOST="localhost"
PORT="61616" CHAN="" TRAN="1" QMGR="MyQCF" />
<Resource name="jms/activeMQQueue" auth="Container"
type="org.apache.activemq.command.ActiveMQQueue" description="my Queue"
factory="org.apache.activemq.jndi.JNDIReferenceFactory" physicalName="userQueue" />
Web.xml content :
<resource-ref>
<res-ref-name>jms/activeMQConnectionFactory</res-ref-name>
<res-type>javax.jms.QueueConnectionFactory</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
<resource-ref>
<res-ref-name>jms/activeMQQueue</res-ref-name>
<res-type>javax.jms.Queue</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
This configuration is OK when aop is not activated but for some reasons, it doesn't work when aop is on..
Spring version : 3.1.2
I'm using activemq (5.7)
I found out what was the problem..
Turns out the aop was not even involved (at least not the configuration that i put). I had some jar in my tomcat server that was not taken for some reasons (i think it's about lib priority/ parent first/last)...
I changed the location and directly put into my project and it works now ! :)

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>

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

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.

Resources