NOTE: Source Code available for download at the bottom of the page
If you are new to JPA, reading basics of JPA HERE is recommended.
What are we going to learn?
We will learn to use JPA with Spring. We will use Hibernate implementation for JPA.
What's needed?
-
Maven
-
JDK 1.5 or higher
-
eclipse
Employee table
CREATE TABLE `employeestore`.`employee` (
`employee_id` INT NOT NULL,
`name` VARCHAR(45) NULL,
`age` VARCHAR(45) NULL,
PRIMARY KEY (`employee_id`));
Following Steps summarize the process for persisting employee using JPA.
-
Create maven project.
-
Update necessary libraries in pom file .
-
Create persistence.xml to hold the database properties for hibernate jpa implementation to pick up.
-
Create Spring Application Context to create and manage beans.
-
Create Employee entity class and provide mapping for the persistent fields.
-
Run main method to create an employee record and fetch record.
Step 1: Create maven project.
Create a maven project of artifact "maven-archetype-quickstart" as shown below.
If resources source folder is not created, create resources folder under src/main/
Step 2: Update necessary libraries in pom file.
We need following artifacts for our project
-
hibernate-jpa-2.0-api
-
hibernate-entitymanager
-
mysql-connector-java
-
spring-context
-
spring-orm
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.visionjava</groupId>
<artifactId>SpringJPAHibernate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringJPAHibernate</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.0.1.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.28</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
</dependencies>
</project>
Step 3: Create persistence.xml to hold the database properties for hibernate jpa implementation to pick up.
-
If resources sources folder is not created, create resources folder under src/main/
-
Create META-INF folder under resources.
-
persistence.xml should be under METS-INF folder
<?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_1_0.xsd"
version="1.0">
<persistence-unit name="visionJavaEmployeeStorePersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/employeestore" />
<property name="hibernate.connection.username" value="visionjava" />
<property name="hibernate.connection.password" value="visionjava" />
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.transaction.flush_before_completion" value="true" />
</properties>
</persistence-unit>
</persistence>
persistence-unit name="visionJavaEmployeeStorePersistenceUnit" is the name of the persistence unit for our database. The name should be unique and if you need multiple data sources, you can create persistence-units with different names. We will use this name for loading our entity manager.
Step
4: Create Spring Application Context to create and manage beans.
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
">
<context:component-scan base-package="com.visionjava" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<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="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
</bean>
</beans>
Step 5: Create Service Layer
package com.visionjava.SpringJPAHibernate.service;
import com.visionjava.SpringJPAHibernate.model.Employee;
public interface EmployeeService {
public int insertEmployee(Employee employee);
public Employee fetchEmployee(int i);
public Employee fetchEmployeeUsingJPAQuery(int i);
}
package com.visionjava.SpringJPAHibernate.service;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.visionjava.SpringJPAHibernate.model.Employee;
@Component("employeeService")
public class EmployeeServiceImpl implements EmployeeService{
@PersistenceContext(unitName = "visionJavaEmployeeStorePersistenceUnit")
private EntityManager entityManager;
@Transactional
public int insertEmployee(Employee employee) {
//entityManager.getTransaction().begin();
entityManager.persist(employee);
//entityManager.getTransaction().commit();
return 1;
}
public Employee fetchEmployee(int i) {
return entityManager.find(Employee.class, i);
}
public Employee fetchEmployeeUsingJPAQuery(int i) {
Query query = entityManager.createQuery("from Employee e where e.employeeId=?");
query.setParameter(1, i);
List result = query.getResultList();
if( result != null){
return (Employee)result.get(0);
}else{
return null;
}
}
}
Step 6: Create EmployeeEntity entity class and provide mapping for the persistent fields.
package com.visionjava.SpringJPAHibernate.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="employee") // Name of the table to which we are associating this Entity
public class Employee {
public Employee() {
super();
}
@Id // Indicates this field as primary key
@Column(name="employee_id", nullable=false)
private int employeeId;
@Column(name="name", nullable=false) //name indicates the name of the column in database
private String employeeName;
@Column(name="age", nullable=false)
private int age;
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Employee(int employeeId, String employeeName, int age) {
super();
this.employeeId = employeeId;
this.employeeName = employeeName;
this.age = age;
}
}
Step 6: Run main method to create and fetch an employee record.
TestSpringJPAHibernate
package com.visionjava.SpringJPAHibernate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.visionjava.SpringJPAHibernate.model.Employee;
import com.visionjava.SpringJPAHibernate.service.EmployeeService;
/**
* Hello world!
*
*/
public class TestSpringJPAHibernate
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeService employeeService = (EmployeeService) context.getBean("employeeService");
employeeService.insertEmployee(new Employee(10,"krishna",25) );
Employee fetchedEmployee = employeeService.fetchEmployee(10);
System.out.println(fetchedEmployee.getAge() + fetchedEmployee.getEmployeeName() );
fetchedEmployee = employeeService.fetchEmployeeUsingJPAQuery(10);
System.out.println(fetchedEmployee.getAge() + fetchedEmployee.getEmployeeName() );
}
}
Project Structure: