Introduction
In my previous post, I have wrote an article about “Spring application with JDBC support” using the Spring class “JpaTemplate” to access an EntityManager. But while pondering the net, I came to know that spring also offers an extensive support for plain API DAO’s. Eventually I understand, the standard way to handle JPA in Spring is to inject the EntityManager with @PersitentContext annotation. So in this article let us learn how to create a sample application using Spring3.04 + JPA 2.0 with JDBC support using JPA’s plain native API for a similar example which I had mentioned in my previous post.
Things You’ll Need
- JDK 1.5 and above
- Latest Spring Framework
- Your favourite IDE
Let us construct the sample application by following the seven steps given below,
- Setting up for the sample application
- Creation of the Database table
- Persistence.xml
- Creation of Entity class
- The DAO Layer
- Spring’s applicationContext.xml file
- Writing tests to verify functionality
Step 1 – Setting up for the sample application
Let us develop the sample application using the following technologies,
Application framework: Spring 3.04
ORM Framework: JPA 2.0
Persistence Provider: Hibernate 3.6.0
Database: My SQL(Or any other database)
Required Jars
The Jar files required for the sample application is given below,
- Spring3.04 jars(Download, Extract and add the jar files in the library folder)
- Hibernate 3.6.0 dependency jars
- commons-logging.jar
- mysqljdbc.jar
- aopalliance.jar
We shall add the above jars in the projects library folder manually. Alternatively you can also use Maven to build the jar files for the project. The library folder should look like the below,
Step 2 – Creation of Database table
Create a database table named “UserDetail”, which contains two columns “userId” and “userName” by executing the following script,
CREATE TABLE `UserDetail` ( `userId` int(11) NOT NULL, `userName` varchar(10) NOT NULL, PRIMARY KEY (`userId`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1
Step 3 – Persistence.xml
The persistence.xml file drives the the JPA ORM layer and let us create a persistence.xml file in the folder named “META-INF”. Let us define the persistence unit name as “SampleTestPU”, and the transaction type as RESOURCE_LOCAL. it should looks like the below,
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="SampleTestPU" transaction-type="RESOURCE_LOCAL"> </persistence-unit> </persistence>
Step 4 – Creation of Entity class
Once the persistence.xml is composed, Next we need to write the entity class for our sample application and let us name the entity class as “UserDetail” which contains userId and user name and it looks like the following,
UserDetail.java
package com.sample.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author giftsam
*/
@Entity
@Table(name = "UserDetail")
public class UserDetail implements Serializable
{
@Id
@Column(name = "userId", nullable = false)
private Integer userId;
@Column(name = "userName", nullable = false)
private String userName;
/**
* Returns a hash code value for the object. This implementation computes
* a hash code value based on the id fields in this object.
* @return a hash code value for this object.
*/
@Override
public int hashCode()
{
int hash = 0;
hash += (this.userId != null ? this.userId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object)
{
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof UserDetail))
{
return false;
}
UserDetail other = (UserDetail) object;
if (this.userId != other.userId
&&(this.userId == null || !this.userId.equals(other.userId)))
{
return false;
}
return true;
}
/**
* Returns a string representation of the object. This implementation constructs
* that representation based on the id fields.
* @return a string representation of the object.
*/
@Override
public String toString()
{
return "com.sample.entity.UserDetail["
+ "userId=" + userId + "]";
}
/**
* @return the userId
*/
public Integer getUserId()
{
return userId;
}
/**
* @param userId the userId to set
*/
public void setUserId(Integer userId)
{
this.userId = userId;
}
/**
* @return the userName
*/
public String getUserName()
{
return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName)
{
this.userName = userName;
}
}
Step 5 – The DAO Layer
Now its time to develop the DAO layer of the application. This layer consists of just one interface “UserDao” and it’s implementation class “UserDaoImpl”. The interface consists of three methods named “createUser(UserDetail userDetail)“, “getAllUserNames()” and “deleteUser(UserDetail userDetail)” and the implementation class “UserDaoImpl” is used to communicate with the database using the entity class UserDetail. it should looks like the below,
UserDao.java
package com.sample.dao;
import com.sample.entities.UserDetail;
import java.util.List;
/**
* @author giftsam
*/
public interface UserDao
{
/**
* This method is used to create the user
*/
void createUser(UserDetail userDetail);
/**
* This method is used to get all the user names from the table UserDetail
* @return list of user names
*/
List<String> getAllUserNames();
/**
* This method is used to delete an user
* @param userDetail
*/
void deleteUser(UserDetail userDetail);
}
UserDaoImpl.java
package com.sample.dao;
import com.sample.entities.UserDetail;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;
/**
* @author giftsam
*/
public class UserDaoImpl implements UserDao
{
private EntityManager entityManager;
@PersistenceContext
public void setEntityManager(EntityManager entityManager)
{
this.entityManager = entityManager;
}
/**
* This method is used to create the user
*/
@Transactional
public void createUser(UserDetail userDetail)
{
entityManager.persist(userDetail);
}
/**
* This method is used to get all the user names from the table User Detail
* @return list of user names
*/
public List<String> getAllUserNames()
{
return entityManager.createQuery("Select s.userName from UserDetail s").getResultList();
}
/**
* This method is used to delete an user
* @param userDetail
*/
@Transactional
public void deleteUser(UserDetail userDetail)
{
entityManager.remove(userDetail);
}
}
Step 6 – Spring’s applicationContext.xml
Now we have come to the main part, we need to create the applicationContext.xml file, the following beans should be defined in the applicationContext.xml file,
entityManagerFactory – The implementation class attribute for the bean “entityManagerFactory” is
“org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean”. The persistence unit name “SampleTestPU” and the provider propeties are defined.
userDao – The implementation class attribute for the bean “userDao” is “com.sample.dao.UserDaoImpl”.
dataSource – The implementation class attribute for the bean “dataSource” is “org.springframework.jdbc.datasource.DriverManagerDataSource”” and JDBC properties are defined.
Transaction manager is used to make the transactions with plain SQL or with plain JDBC by using Hibernate (or any other ORM library) or by using EJB or Spring. The implementation class for the bean “transactionManager” is “org.springframework.orm.jpa.JpaTransactionManager”.
persistenceAnnotation – The implementation class attribute for the bean “persistenceAnnotation” is “org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor”.
applicationContext.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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceUnitName" value="SampleTestPU"/> <property name="dataSource" ref="dataSource"/> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="showSql" value="true"/> <property name="generateDdl" value="false"/> <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/> </bean> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://192.0.0.1:3306/Sample-Application"/> <property name="username" value="admin"/> <property name="password" value="admin123"/> </bean> <bean id="userDao" class="com.sample.dao.UserDaoImpl"> </bean> <tx:annotation-driven/> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> <property name="dataSource" ref="dataSource"/> </bean> <bean id="persistenceAnnotation" class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> </beans>
Step 7 – Writing tests to verify functionality
Finally we come to last stage of our sample application development, Now its time to test our application. For that we shall write a ordinary POJO java class named “Tester” and it should looks like the below,
Tester.java
package com.sample.tester;
import com.sample.dao.UserDao;
import com.sample.entities.UserDetail;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author giftsam
*/
public class Tester
{
/**
* @param args
*/
public static void main(String[] args)
{
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("config/applicationContext.xml");
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
UserDetail userDetail = new UserDetail();
userDetail.setUserId(1);
userDetail.setUserName("Freddy");
userDao.createUser(userDetail);
System.out.println("User is successfully created");
System.out.println("User names is: " + userDao.getAllUserNames());
}
}
I reckon, you should have get the exact result while executing the above program. Last but not least, let us take a look on the project structure of our sample application.
Project Structure
The project structure of our created sample application looks like the below,
Thats all folks. I hope this article clearly explains the sample application development of Spring 3.04 + JPA 2.0 with JDBC support using JPA’s plain native API’s. If you find this article is useful for you, dont forget to leave your valuable comments. Have a joyous code day.


Very nice.
I can’t believe SpringSource is making it even easier to do JPA nowadays.
Well-loved. Like or Dislike:
6
0
[Reply]
Oliver Gierke Reply:
December 22nd, 2010 at 11:20 pm
It will even become easier: we can drop most of the implementation code for repositories. See this infoq article for details: http://www.infoq.com/articles/hades_jpa_repositories_done_right
The project will soon be integrated into the Spring Data Project.
Cheers,
Ollie
- Hades Project Lead
[Reply]
[...] dont want to use “JpaTemplate”, Instead I want to use JPA’s native API. The post Spring 3.0 + JPA 2.0 using plain API DAO’s gives you the guidelines for SpringDao using JPA’s native API. If you find this article is [...]
Do you really need to define the datasource for the transaction manager ?
45
46
47
as it uses a entitymanagerfactory which is already bound to a datasource ?
Regards,
Bernard.
[Reply]
giftsam Reply:
December 11th, 2010 at 11:35 am
Hi biligny,
Thanks for your comment and a very good question. If you set default-autowire=”byName” in the beans tag means, it is not neccessary to define the entity manager and data source property in the transaction manager. Also it is not necessary to define the datasource property in the entitymanager bean. So if you dont want to define this properties, set the attribute default-autowire=”byName” in the beans tag.
Thanks – Gift Sam
[Reply]
Hi Sam,
Thanks for your quick reply. Actually my question was not really about autowiring but rather about injection redundancy of the datasource.
Indeed:
- the transaction manager is bound to the entity factory factory
- this entityManagerFactory is using a datasource
=> so, by transitivity, the transacion manager is also (indirectly but yet) wired to a datasource – true ?
So why do we have to *again* link the transaction manager to out datasource ?
Bernard.
[Reply]
Dec 14, 2010 11:18:57 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@a8c488: startup date [Tue Dec 14 11:18:57 EST 2010]; root of context hierarchy
Dec 14, 2010 11:18:57 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from URL [file:/C:/Documents%20and%20Settings/lidkv15/Galileo/workspace/SpringJPA2/build/classes/com/springjpa/test/applicationContext.xml]
Dec 14, 2010 11:18:58 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@da3a1e: defining beans [persistenceUnitManager,entityManagerFactory,dataSource,personDAO,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,persistenceAnnotation]; root of factory hierarchy
Dec 14, 2010 11:18:58 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Dec 14, 2010 11:18:58 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@da3a1e: defining beans [persistenceUnitManager,entityManagerFactory,dataSource,personDAO,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,persistenceAnnotation]; root of factory hierarchy
Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ defined in URL [file:/C:/Documents%20and%20Settings/lidkv15/Galileo/workspace/SpringJPA2/build/classes/com/springjpa/test/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No persistence unit with name ‘SpringJPA2′ found
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:563)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.springjpa.test.PersonJPATest.main(PersonJPATest.java:21)
Caused by: java.lang.IllegalArgumentException: No persistence unit with name ‘SpringJPA2′ found
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.obtainPersistenceUnitInfo(DefaultPersistenceUnitManager.java:393)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.determinePersistenceUnitInfo(LocalContainerEntityManagerFactoryBean.java:244)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:196)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:308)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
… 12 more
[Reply]
giftsam Reply:
December 15th, 2010 at 7:24 am
Hi Shiva,
The error is,
“Caused by: java.lang.IllegalArgumentException: No persistence unit with name ‘SpringJPA2? ”
Check whether the entity manager bean definition in the applicationContext.xml file contains the correct persistence unit name “SpringJPA2″.
Thanks – Giftsam
[Reply]
can you provide the link for “com.springsource.org.aopalliance-1.0.0.jar”?
thanks.
[Reply]
giftsam Reply:
December 16th, 2010 at 1:05 pm
Hi Reza,
You can download from the following link,
http://tinyurl.com/2asmtgg
[Reply]
I am getting error while I build my SpringJPA application. It says:
Line 12 in XML document from ServletContext resource [/WEB-INF/applicationContext.xml] is invalid;
nested exception is oracle.xml.parser.schema.XSDException: Duplicated definition for: ‘identifiedType’
It seems like error in parsing the xml. I am using OC4J server. Do I need to add any specific JAR file in my “applib”? or any suggestions?
[Reply]
Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ defined in class path resource [config/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No persistence unit with name ‘SampleTestPU’ found
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1401)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:540)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:842)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:416)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.sample.tester.Tester.main(Tester.java:17)
Caused by: java.lang.IllegalArgumentException: No persistence unit with name ‘SampleTestPU’ found
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.obtainPersistenceUnitInfo(DefaultPersistenceUnitManager.java:379)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.determinePersistenceUnitInfo(LocalContainerEntityManagerFactoryBean.java:244)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:196)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1460)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1398)
… 12 more
[Reply]
What could be the possible causes of that error ?
I have checked META-INF folder many times but no solution
[Reply]
giftsam Reply:
February 2nd, 2011 at 11:45 pm
Hi ilqar,
Did you configured persistence.xml file as specified in the step 3, because the error specifies there is no persistence unit name “SampleTestPU”. Kindly check it out and come back to me if the problem still exists.
Thanks – GiftSam
[Reply]
HI,
How to configure this example for Jdbc-Odbc??
Thanks in advance:)
[Reply]
I tried to do the example. But it can’t run. Some jar files are missing. Please can anybody give the jar files.
Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError: org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(Ljavax/persistence/spi/PersistenceUnitInfo;Ljava/util/Map;)Ljavax/persistence/EntityManagerFactory;
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:563)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.sample.tester.Tester.main(Tester.java:17)
Caused by: java.lang.AbstractMethodError: org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(Ljavax/persistence/spi/PersistenceUnitInfo;Ljava/util/Map;)Ljavax/persistence/EntityManagerFactory;
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:242)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:308)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1479)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
… 12 more
[Reply]
I am also getting exactly the same error.
[Reply]
You need to make sure you have got the compatible versions of slf4j jars I am running with version 1.6.1 of slf4j-api and slf4j-simple and things are now good
[Reply]
I am getting exactly same error.. did you find out the sollution..?
[Reply]
giftsam Reply:
September 21st, 2011 at 2:59 pm
Kindly make sure, You have the same versions of Jars as specified in the article.Incase if you use latest jars then it should be compatible with the other jars.
[Reply]
i all.
I have tried spring with a web apèplication.
I have a question:
if into a controller i would set for the Moedl 2 or plus object for viewer it into a page ,how i have to set objcets???????
for example into the page jps taht the user view afeter that controller manage the request , i have a ogets with reuest scopedand ù2 wtihe sesson scoped
mauro
[Reply]
Im also getting the below exception , while running this example . I have same version’s of as per given in lib screen shot. Please guide me .
[INFO] ClassPathXmlApplicationContext – -Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@18a47e0: startup date [Fri Mar 30 10:14:02 GMT+05:30 2012]; root of context hierarchy
[INFO] XmlBeanDefinitionReader – -Loading XML bean definitions from class path resource [conf/applicationContext.xml]
[INFO] DefaultListableBeanFactory – -Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1b8e059: defining beans [entityManagerFactory,dataSource,userDao,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,persistenceAnnotation]; root of factory hierarchy
[INFO] DriverManagerDataSource – -Loaded JDBC driver: com.mysql.jdbc.Driver
[INFO] LocalContainerEntityManagerFactoryBean – -Building JPA container EntityManagerFactory for persistence unit ‘SampleTestPU’
[INFO] DefaultListableBeanFactory – -Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1b8e059: defining beans [entityManagerFactory,dataSource,userDao,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,persistenceAnnotation]; root of factory hierarchy
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ defined in class path resource [conf/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError: org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(Ljavax/persistence/spi/PersistenceUnitInfo;Ljava/util/Map;)Ljavax/persistence/EntityManagerFactory;
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:563)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.sample.tester.Tester.main(Tester.java:18)
Caused by: java.lang.AbstractMethodError: org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(Ljavax/persistence/spi/PersistenceUnitInfo;Ljava/util/Map;)Ljavax/persistence/EntityManagerFactory;
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:225)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:308)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
… 12 more
[Reply]
hi, I am learning Spring , hoping to move from a mainframe programmer to java web developer. Your configuration for the JPA setup is excellent. The Spring documentation was not as easy to follow as your blog. Excellent stuff, thanks !
[Reply]
The above Spring + JAP example is very good.
To avoid -No persistence unit with name ‘SampleTestPU’ found and other errors.
Try to use above exact jar version properly.
I hope now you people wont face any issues…
1. src\META-INF\persistence.xml
2. class path or under src\applicationContext.xml
Thanks.,
–Mani
[Reply]
Nice tutorial, thanks.
I have one thing to add. Usually the transactional annotations (@Transactional) are used in the service layer instead of in the DAO layer like in this example.
Using them in the DAO layer like this will give you a “one transaction per CRUD operation” pattern. Putting @Transactional on a service method will enable you to call multiple DAO methods in that method that are all in the same transaction. In other words, you will get a “one transaction per business transaction” pattern, which is better.
Imagine a banking app. If you transfer 10 dollars from bank account A to bank account B you need three operations.
- check if A has enough credit to deduct 10 dollar.
- deduct 10 dollar from A
- add 10 dollar to B
These can be seen as 3 DAO methods. The business transaction is 1 service method that calls these 3 DAO methods. You want the entire operation to succeed or be rolled back. That is why you can better use @Transactional transaction demarcation in the service layer.
[Reply]
Thanks!
[Reply]
Hi,
I have two DAO Impl classes, the entity manager is being injected in one impl class but it is null in the other.
Can you please let me know, can I use @PersistenceContext in more than one DAOImpl Class, in one class I am using merge and flush and in other i am using it to retrieve an object,
My usecase: Is to persist an Entity, which has a mapping to another Entity as foreign key.
I am using Spring 3.0 + JPA2.0 + Hibernate 4.0
Any help is highly appreciated.
Thanks,
Gopi.
[Reply]