In this article, I will show you an example of JPA using spring. We will use spring to configure EntityManagerFactory
and inject its bean to our DAO object. If you want to get a feel of JPA without the use of spring, see Hibernate JPA Example.
Dependencies
We are dependent on the following modules:
spring-context
– for access to spring context.spring-orm
– we need this for creatingEnityManagerFactory
.hibernate-entitymanager
– we are using hibernate as our JPA engine so we need this.mysql-connector-java
– we are using mysql as our database so this our mysql driver
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javarticles.jdbc.datasource</groupId> <artifactId>springdatasource</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.26</version> </dependency> </dependencies> <properties> <spring.version>4.1.5.RELEASE</spring.version> <hibernate.version>4.3.8.Final</hibernate.version> </properties> </project>
Hibernate Configuration File
We hibernate as our JPA engine so let’s set our database details in the hibernate configuration XML.
hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">mnrpass</property> <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hbm2ddl.auto">update</property> </session-factory> </hibernate-configuration>
Persistence Configuration
persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <persistence-unit name="employee_persistence_unit"> <properties> <property name="hibernate.ejb.cfgfile" value="/hibernate.cfg.xml" /> </properties> </persistence-unit> </persistence>
Spring Application Context
Spring encapsulates the EntityManagerFactory
in its own FactoryBean
implementation org.springframework.orm.jpa.LocalEntityManagerFactoryBean
.
This FactoryBean
creates the EntityManagerFactory
for standalone environments.
Let’s define the LocalEntityManagerFactoryBean
in our configuration file. We need to set the persistenceUnitName
to the persitence-unit
name provided in the
persistence.xml
file.
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="employee_persistence_unit" /> </bean> </beans>
Employee DAO
Employee:
package com.javarticles.spring.jpa; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="emp") public class Employee { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; @Column(name="name", length=100, nullable=false) private String name; @Column(name="contract", length=100) private String contact; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String toString() { return "Employee: " + name; } }
EmployeeDao:
package com.javarticles.spring.jpa; import java.util.List; public interface EmployeeDao { List<?> findEmployees(); void deleteEmployees(List<?> empList); void createEmployee(String Name); void saveEmployee(Employee employee); }
We implement our employee DAO using EntityManager
API. We have methods to find, delete and create employees.
EmployeeJpaDao:
package com.javarticles.spring.jpa; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.TypedQuery; public class EmployeeJpaDao implements EmployeeDao { private EntityManagerFactory entityManagerFactory; private EntityManager entityManager; public void init() { entityManager = entityManagerFactory.createEntityManager(); } public List<?> findEmployees() { TypedQuery empQuery = entityManager.createQuery("from Employee where name in (?, ?)", Employee.class); empQuery.setParameter(1, "Joe"); empQuery.setParameter(2, "Sam"); List empList = empQuery.getResultList(); System.out.println("Employees found: " + empList.size()); return empList; } public void deleteEmployees(List<?> empList) { if (!empList.isEmpty()) { for (Object emp : empList) { entityManager.remove(emp); } System.out.println("Employees deleted"); } } public void createEmployee(final String Name) { System.out.println("Create new employee " + Name); Employee emp = new Employee(); emp.setName(Name); entityManager.persist(emp); System.out.println("Employee created " + emp); } public void saveEmployee(Employee emp) { System.out.println("Create new employee " + emp); entityManager.persist(emp); System.out.println("Employee created " + emp); } public void setEntityManagerFactory( EntityManagerFactory entityManagerFactory) { this.entityManagerFactory = entityManagerFactory; } }
Let’s inject entityManagerFactory
factory into EmployeeDao
. We create the EntityManager
from the factory in its init()
method.
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="employee_persistence_unit" /> </bean> <bean id="employeeDao" class="com.javarticles.spring.jpa.EmployeeJpaDao" init-method="init"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> </beans>
Data Access Operations Using JPA
We can use EntityManager
API to execute data access operations such as creating, finding, and deleting entities. Our class SpringJpaExample
will use EmployeeDao
to do some operations on employee data.
In the spring context XML, we configure springJpaExample
and inject employeeDao
bean for the database operations on employee.
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="employee_persistence_unit" /> </bean> <bean id="employeeDao" class="com.javarticles.spring.jpa.EmployeeJpaDao" init-method="init"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <bean id="springJpaExample" class="com.javarticles.spring.jpa.SpringJpaExample"> <property name="employeeDao" ref="employeeDao"/> </bean> </beans>
In the execute()
, we first delete all the employees. Next, we create couple of new employees and save.
Finally, we retrieve the created employees.
SpringJpaExample:
package com.javarticles.spring.jpa; import java.io.IOException; import java.util.List; import org.hibernate.MappingException; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringJpaExample { private EmployeeDao empDao; public static void main(String[] args) throws MappingException, IOException { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml"); try { SpringJpaExample springJpaDao = (SpringJpaExample) context .getBean("springJpaExample"); springJpaDao.execute(); } finally { context.close(); } } public void execute() { List<?> empList = empDao.findEmployees(); empDao.deleteEmployees(empList); empDao.createEmployee("Joe"); Employee empSam = new Employee(); empSam.setName("Sam"); empDao.saveEmployee(empSam); System.out.println("List of employees: " + empDao.findEmployees()); } public void setEmployeeDao(EmployeeDao empDao) { this.empDao = empDao; } }
Output:
Employees found: 2 Employees deleted Create new employee Joe Employee created Employee: Joe Create new employee Employee: Sam Employee created Employee: Sam Employees found: 2 List of employees: [Employee: Joe, Employee: Sam]
Download source code
This was an example about JPA using spring. You can download the source code here: springJpaExample.zip