I am trying to configure LocalContainerEntityManagerFactoryBean without persisten.xml file.
this is my dataSource - it works for Hibernate SessionFactory - so, it is ok.
<bean id="dataSource"
class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
this is my LocalContainerEntityManagerFactoryBean
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="application.models" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
An exception that i am getting:
...Could not instantiate bean class [org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter]: Constructor threw exception; nested exception is java.lang.IllegalStateException: Failed to determine Hibernate PersistenceProvider
I read documentation, and i know that LocalContainerEntityManagerFactoryBean has such property, and similar style of creating LocalContainerEntityManagerFactoryBean works in Spring in Action 3 and here: http://softwarecave.org/2014/03/15/using-jpa-and-jta-with-spring/
Maybe You have an idea what i am doing wrong or at least what spring want tell me via this exception ?
Thanks in advance,
Cheers :)
P.S to be clear, Failed to determine Hibernate PersistenceProvider doesn't mean that spring expect persistence.xml - this should be error like: No persistence units parsed from {classpath*:META-INF/persistence.xml}
RESOLVED:
thanks JB Nizet - if You will have similar problem add:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.6.Final</version>
</dependency>
to pom.xml
Below code works for me.
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" p:dataSource-ref="dataSource">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
With hibernate = 4.3.5.Final
spring=4.1.4.RELEASE
Related
I continue getting the following error:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'StorageItemRepository'
My beans.xml is set to find all - located in META-INF/beans.xml of every module resource file. My Repository class does have #Repository on it and my web.xml is definitely configured to find the bean.
It's worth noting - this working when deployed - just not for the below unit test.
My unit test:
/**
* Test for {#link StorageItemRepository}
*/
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration({"classpath:JDBCConfig.xml"})
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = {"com.app.storage.persistence.repository"})
public class StorageItemRepositoryTest {
/** {#link StorageItemRepository} */
#Autowired
private StorageItemRepository storageItemRepository;
/**
* Finds all storage items in db.
*/
#Test
public void checkFindAllItems(){
final StorageItemPersistenceModel storageItemPersistenceModel = new StorageItemPersistenceModel();
storageItemPersistenceModel.setId(1L);
storageItemPersistenceModel.setDateStored(new DateTime());
storageItemPersistenceModel.setName("Name");
storageItemRepository.save(storageItemPersistenceModel);
}
}
JDBCConfig file:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/storage_app_schema" />
<property name="username" value="root" />
<property name="password" value="dollar123" />
</bean>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="packagesToScan" value="com.app.storage.persistence.model" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<property name="persistenceUnitName" value="app_test"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</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.MySQLDialect"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf"/>
</bean>
</beans>
The persistence.xml is definitely fine and working so not the cause.
How are you running the unit test?
Since it is working when deployed, and not in the unit test, I am inclined to suspect that the unit test execution has a missing classpath, such as JDBCConfig.xml doesn't exist in the execution classpath
I'm trying to persist an entity using EntityManagerFactory defined in my bean. The function looks like this:
private BaseMasterEntity saveEntity(BaseMasterEntity entity){
EntityManagerFactory emf = (EntityManagerFactory)context.getBean("entityManagerFactory");
EntityManager sf = emf.createEntityManager();
sf.getTransaction().begin();
sf.persist(entity);
sf.getTransaction().commit();
sf.close();
return entity;
}
The problem here is when it persists it cannot find the entity. The entity has #Entity defined clearly with the javax.persistance annotation. This is how my context file looks btw:
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="*my jdbc setting*" />
<property name="username" value="hr" />
<property name="password" value="hr" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
<property name="packagesToScan"
value="classpath*:com.samplewebentities"></property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="hibernateJpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
<tx:annotation-driven transaction-manager="transactionManager" />
If it helps, the classpath*:com.samplewebentites is a different component (The application is a combination of many different components/projects: Using SCA here).
No need for classpath
..
<property name="packagesToScan"
value="com.samplewebentities"></property>
..
I previously had this config for Hibernate using RESOURCE-LOCAL transaction type:
persistence.xml:
<persistence-unit name="myPU" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
</persistence-unit>
applicationContext (dataaccess bit):
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entityManagerFactory-ref="entityManagerFactory"></bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaAdapter" />
<property name="persistenceUnitName" value="myPU"/>
<property name="jpaProperties">
<props>
<prop key="javax.persistence.validation.mode">none</prop>
</props>
</property>
</bean>
<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<!-- Are there any other properties required? -->
</bean>
<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
</bean>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/CNTXESDB" />
<property name="lookupOnStartup" value="true" />
<property name="cache" value="true" />
<property name="proxyInterface" value="javax.sql.DataSource" />
</bean>
But this kind of transaction seems not to work with Glassfish, so I had to switch to JTA transactions.
The problem is -- to get Spring to manage transaction creation (through #Transactional) I need to define a TransactionManager bean but JtaTransactionManager included in spring-tx does not accept an entityManagerFactory bean, so it does not know where the entityManager is in order to open/close/flush Hibernate session.
So how can I configure Spring with Hibernate to use JTA transactions?
EDIT:
turns out you can use RESOURCE_LOCAL transactions with Glassfish, but somehow you cannot have a persistence.xml file. I renamed this file to my_persistence.xml and configured LocalContainerEntityManagerFactoryBean like this:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaAdapter" />
<property name="persistenceUnitName" value="myPU"/>
<property name="persistenceXmlLocation" value="classpath:META-INF/my_persistence.xml" />
<property name="jpaProperties">
<props>
<prop key="javax.persistence.validation.mode">none</prop>
</props>
</property>
</bean>
I had a similar problem and finally I solved as you can see in this little demo:
https://github.com/miguelangelprogramacion/spring4_jpa_hibernate
With [1] as a reference, I prefer to use Spring's Transaction Support before JTA.
Also, I've used an annotation based approach.
[1] http://spring.io/blog/2011/08/15/configuring-spring-and-jta-without-full-java-ee/
I have successfully configured hibernate and I can run transactions but only from the psvm of the DAO class. I want to configure it with my spring app using the same configuration file i.e. hibernate.cfg.xml.
How can I do this? Most tutorials I've read simply neglect the hibernate configuration file.
You can add this code to you xml file to configure hibernate.
<!-- Hibernate Related Configuration. -->
<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://192.168.1.9:5432/dbname"/>
<property name="username" value="postgres"/>
<property name="password" value="pwd"/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.domain"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
The hibernate.cfg.xml file is specified for the LocalEntityManagerFactoryBean, along with your DataSource
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath*:META-INF/hibernate.cfg.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
Here you can find an example of a Spring XML configuration containing some Hibernate configuration
I´ve my hibernate configuration inside my spring-context, but after a little time of use I´m getting the too many connections error. Here is my code:
Spring context:
<!-- Beans Declaration -->
<bean id="Usuarios" class="com.proximate.model.Usuarios"/>
<!-- Service Declaration -->
<bean id="UsuariosService" class="com.proximate.service.UsuariosService">
<property name="usuariosDAO" ref="UsuariosDAO" />
</bean>
<!-- DAO Declaration -->
<bean id="UsuariosDAO" class="com.proximate.dao.UsuariosDAO">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
<bean id="DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mydb" />
<property name="user" value="user" />
<property name="password" value="password" />
<property name="maxPoolSize" value="50" />
<property name="maxStatements" value="0" />
<property name="minPoolSize" value="5" />
</bean>
<!-- Session Factory Declaration -->
<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="DataSource" />
<property name="annotatedClasses">
<list>
<value>com.proximate.model.Usuarios</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<!-- Enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager"/>
<context:annotation-config />
<!-- Transaction Manager is defined -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory"/>
</bean>
and here is how I use my session factory inside my dao:
private SessionFactory sessionFactory;
private HibernateTemplate hibernateTemplate;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
Query query = hibernateTemplate.getSessionFactory().getCurrentSession().createSQLQuery("SELECT ID FROM usuarios");
Integer cantidad = new Integer(((BigInteger) query.uniqueResult()).intValue());
Why is my code opening so many connections. I heard that using a HibernateUtil class to load a session after logging might be what I need, but how do you implement it when using spring??
Thanks in advance!!
I don't know much about hibernate itself, but i think closing the session might help.
That's how JPAs EntityManager works - you have to close it to close underlaying connection.
It looks like your hibernate query is global? I would guess the cause is probably because it is not contained in a method with a transactional annotation around it.