Home » Enterprise Java » spring » Spring Data JPA Example

About Ram Mokkapaty

Ram Mokkapaty
Ram holds a master's degree in Machine Design from IT B.H.U. His expertise lies in test driven development and re-factoring. He is passionate about open source technologies and actively blogs on various java and open-source technologies like spring. He works as a principal Engineer in the logistics domain.

Spring Data JPA Example

The goal of Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores. If we try to implement a data access layer of an application on our own, we will end up with lots of boilerplate code.

Spring provides JPA module which not only eliminates boilerplate code but also takes care of the CRUD operations, provides inbuilt implementation for simple queries, performs pagination and auditing. Using Spring Data JPA we can write our own repository interfaces, including custom finder methods, and Spring will provide the implementation automatically. In this article we will see some examples of Spring Data JPA.

1. Dependencies

Since we are using Spring Data Jpa, we certainly need to add spring-data-jpa. We also need a database. In this example, we will use HSQL database in embedded mode. We will use hibernate as the JPA vendor so you need to add hibernate-jpa-2.0-api and hibernate-entitymanager. Other than that we also need the spring-core and spring-context.

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.javacodegeeks.camel</groupId>
	<artifactId>springQuartzScheduler</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.1.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.1.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-jpa</artifactId>
			<version>1.8.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.hsqldb</groupId>
			<artifactId>hsqldb</artifactId>
			<version>2.2.9</version>
			<scope>runtime</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.3.10.Final</version>
			<scope>runtime</scope>
		</dependency>

	</dependencies>
</project>

2. Entity Bean

Let’s first define an entity bean. It is an employee class, marked with @Entity. It has two columns, age and name. Other than these two,there is an auto-generated ID column.

Employee:

package com.javacodegeeks.spring.jpa;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Employee {
	@Id
	@GeneratedValue
	private Long id;
	private String name;
	private Integer age;

	public Employee(){}
	
	public Employee(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	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 Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}	

	public String toString() {
		return "Employee (" + getId() + ", " + getName() + ", " + age + ")";
	}
	
	@Override
	public boolean equals(Object obj) {

		if (this == obj) {
			return true;
		}

		if (this.id == null || obj == null || !(this.getClass().equals(obj.getClass()))) {
			return false;
		}

		Employee o = (Employee) obj;

		return this.id.equals(o.getId());
	}

	@Override
	public int hashCode() {
		return id == null ? 0 : id.hashCode();
	}
}

3. Initialization of Database

We also want to initialize the database with some sample data as the application starts. Here is some sample employee data.

data.sql:

insert into Employee (id, name, age) values (1, 'Joe', 32);
insert into Employee (id, name, age) values (2, 'Sam', 28);
insert into Employee (id, name, age) values (3, 'John', 43);

4. Configure Entity Manager Factory and Transaction Manager

Let’s begin configuring the entity manager factory and transaction manager.

EntityManagerFactory – An entity manager factory provides entity manager instances, all instances are configured to connect to the same database, to use the same default settings as defined by the particular implementation, etc. You can prepare several entity manager factories to access several data stores. This interface is similar to the SessionFactory in native Hibernate.

EntityManager – This is used to access a database in a particular unit of work. It is used to create and remove persistent entity instances, to find entities by their primary key identity, and to query over all entities. This interface is similar to the Session in Hibernate.

We will use HSQL as the database in embedded mode. To specify HSQL explicitly, set the type attribute of the embedded-database tag to HSQL. If you are using the builder API, call the setType(EmbeddedDatabaseType) method with EmbeddedDatabaseType.HSQL@EnableTransactionManagemen Enables Spring’s annotation-driven transaction management capability.

Using the below JpaConfig</code, we provide DataSource bean, EntityManager factory, transaction manager and a database populator bean.

JpaConfig:

package com.javacodegeeks.spring.jpa;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class JpaConfig {

	/**
	 * Bootstraps an in-memory HSQL database.
	 */
	@Bean
	public DataSource dataSource() {
		EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
		return builder.setType(EmbeddedDatabaseType.HSQL).build();
	}

	/**
	 * Picks up entities from the project's base package.
	 */
	@Bean
	public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

		HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
		vendorAdapter.setDatabase(Database.HSQL);
		vendorAdapter.setGenerateDdl(true);

		LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
		factory.setJpaVendorAdapter(vendorAdapter);
		factory.setPackagesToScan(getClass().getPackage().getName());
		factory.setDataSource(dataSource());

		return factory;
	}

	@Bean
	public PlatformTransactionManager transactionManager() {

		JpaTransactionManager txManager = new JpaTransactionManager();
		txManager.setEntityManagerFactory(entityManagerFactory().getObject());
		return txManager;
	}
	
	@Bean
	@Lazy(false)
	public ResourceDatabasePopulator populateDatabase() throws SQLException {

		ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
		populator.addScript(new ClassPathResource("data.sql"));

		Connection connection = null;

		try {
			connection = DataSourceUtils.getConnection(dataSource());
			populator.populate(connection);
		} finally {
			if (connection != null) {
				DataSourceUtils.releaseConnection(connection, dataSource());
			}
		}
		return populator;
	}
}

5. Configure in Spring XML Context

The same Spring Configuration with XML:

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:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.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="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="packagesToScan" value="com.javacodegeeks.spring.jpa" />
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="database" value="HSQL" />
				<property name="generateDdl" value="true" />
			</bean>
		</property>
	</bean>

	<jdbc:initialize-database data-source="dataSource">
		<jdbc:script location="classpath:data.sql" />
	</jdbc:initialize-database>

	<jdbc:embedded-database id="dataSource" type="HSQL" />

</beans>

6. CRUD Repository

The central interface in Spring Data repository abstraction is Repository interface. It takes the domain class to manage as well as the id type of the domain class as type arguments. This interface acts primarily as a marker interface to capture the types to work with and to help you to discover interfaces that extend this one.

The CrudRepository provides sophisticated CRUD functionality for the entity class that is being managed.

CrudRepository:

public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {

	<S extends T> S save(S entity);

...
	T findOne(ID id);

	Iterable<T> findAll();

	void delete(ID id);

...
}

The repository interface provides the CRUD operations

  1. Saves the given entity.
  2. Returns the entity identified by the given id.
  3. Returns all entities.
  4. Returns the number of entities.
  5. Deletes the given entity.
  6. Indicates whether an entity with the given id exists.

Spring also provides JpaRepository which is JPA specific, provides persistence technology-specific abstractions.

7. Employee Repository

We will now define employee specific repository. We come up with an employee repository extending Repository or one of its sub-interfaces.

If you want to write your own query method, you can use a named query using annotation the Spring Data JPA @Query annotation. Using named queries, we can declare queries for entities.

If you want paging, you either extend PagingAndSortingRepository that provides additional methods to ease paginated access to entities or write one of your own,

EmployeeRepository:

package com.javacodegeeks.spring.repositories;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import com.javacodegeeks.spring.jpa.Employee;


public interface EmployeeRepository extends CrudRepository<Employee,String> {
    List<Employee> findEmployeesByAge(int age);  
    List<Employee> findEmployeesByName(String name);
    @Query("select emp from Employee emp where emp.age >= ?1 and emp.age <= ?2")
    List<Employee> findEmployeesBetweenAge(int from, int to);
    Page<Employee> findEmployeesByAgeGreaterThan(int age, Pageable pageable);
}

8. CRUD Operations using Annotation Based Configuration

In our main class, we need to somehow scan the employee repository so that we have access to the CRUD operations. We will use @EnableJpaRepositories annotation to enable JPA repositories. We will have to provide the base package locations for scanning the package of the annotated configuration class for Spring Data repositories by default.

Using the employee repository we:

  1. Add employees
  2. Query the employees
  3. Accessing employees page wise

SpringDataJpaExampleUsingAnnotation:

package com.javacodegeeks.spring.jpa;

import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.transaction.annotation.Transactional;

import com.javacodegeeks.spring.repositories.EmployeeRepository;

@Configuration("mainBean")
@EnableJpaRepositories(basePackages = "com.javacodegeeks.spring.repositories")
@Import(JpaConfig.class)
@Transactional
public class SpringDataJpaExampleUsingAnnotation {
	@Autowired
	private EmployeeRepository repository;
	
	@Autowired
	private DataSource dataSource;

	public static void main(String[] args) throws URISyntaxException, Exception {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		try {
			ctx.register(SpringDataJpaExampleUsingAnnotation.class);
			ctx.refresh();
			System.out.println("Load context");
			SpringDataJpaExampleUsingAnnotation s = (SpringDataJpaExampleUsingAnnotation) ctx.getBean("mainBean");

			System.out.println("Add employees");
			s.addEmployees();
			System.out.println("Find all employees");
			s.findAllEmployees();
			System.out.println("Find employee by name 'Joe'");
			s.findEmployee("Joe");
			System.out.println("Find employee by name 'John'");
			s.findEmployee("John");
			System.out.println("Find employees by age");
			s.findEmployeesByAge(32);
			System.out.println("Find employees between 30 and 45");
			s.findEmployeesBetweenAge(30, 45);
			System.out.println("Find employees greater than 20");
			s.findEmployeesGreaterThanAgePageWise(20, 1, 0);
			s.findEmployeesGreaterThanAgePageWise(20, 1, 1);
			s.findEmployeesGreaterThanAgePageWise(20, 2, 0);
			s.findEmployeesGreaterThanAgePageWise(20, 2, 1);
		} finally {
			ctx.close();
		}
	}

	public void addEmployees() {
		Employee emp1 = new Employee("Richard", 32);
		Employee emp2 = new Employee("Satish", 30);
		Employee emp3 = new Employee("Priya", 16);
		Employee emp4 = new Employee("Rimi", 30);
		
		repository.save(emp1);
		repository.save(emp2);
		repository.save(emp3);
		repository.save(emp4);
	}

	public void findAllEmployees() {
		repository.findAll().forEach(System.out::println);
	}

	public void findEmployee(String name) {
		List<Employee> empList = repository.findEmployeesByName(name);
		System.out.println("Employee list: " + empList);
	}

	public void findEmployeesByAge(int age) {
		List<Employee> empList = repository.findEmployeesByAge(age);
		System.out.println("Employee list: " + empList);
	}
	
	public void findEmployeesBetweenAge(int from, int to) {
		List<Employee> empList = repository.findEmployeesBetweenAge(from, to);
		System.out.println("Employee list: " + empList);
	}	
	
	public void findEmployeesGreaterThanAgePageWise(int age, int pageSize, int pageNbr) {
		System.out.println("Page size: " + pageSize + ", page " + pageNbr);
		Pageable pageable = new PageRequest(pageNbr, pageSize, Direction.DESC, "name", "age");
		Page<Employee> page = repository.findEmployeesByAgeGreaterThan(age, pageable);
		System.out.println(page.getContent());
	}
}

Output:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Jan 27, 2016 9:22:12 AM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
	name: default
	...]
Jan 27, 2016 9:22:12 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.10.Final}
Jan 27, 2016 9:22:12 AM org.hibernate.cfg.Environment 
INFO: HHH000206: hibernate.properties not found
Jan 27, 2016 9:22:12 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jan 27, 2016 9:22:12 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager 
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Jan 27, 2016 9:22:13 AM org.hibernate.dialect.Dialect 
INFO: HHH000400: Using dialect: org.hibernate.dialect.HSQLDialect
Jan 27, 2016 9:22:13 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory 
INFO: HHH000397: Using ASTQueryTranslatorFactory
Jan 27, 2016 9:22:13 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Jan 27, 2016 9:22:13 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Jan 27, 2016 9:22:13 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
Jan 27, 2016 9:22:13 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: Employee
Jan 27, 2016 9:22:13 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: Employee
Jan 27, 2016 9:22:13 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: Employee
Jan 27, 2016 9:22:13 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Load context
Add employees
Find all employees
Employee (1, Joe, 32)
Employee (2, Sam, 28)
Employee (3, John, 43)
Employee (4, Richard, 32)
Employee (5, Satish, 30)
Employee (6, Priya, 16)
Employee (7, Rimi, 30)
Find employee by name 'Joe'
Employee list: [Employee (1, Joe, 32)]
Find employee by name 'John'
Employee list: [Employee (3, John, 43)]
Find employees by age
Employee list: [Employee (1, Joe, 32), Employee (4, Richard, 32)]
Find employees between 30 and 45
Employee list: [Employee (1, Joe, 32), Employee (3, John, 43), Employee (4, Richard, 32), Employee (5, Satish, 30), Employee (7, Rimi, 30)]
Find employees greater than 20
Page size: 1, page 0
[Employee (5, Satish, 30)]
Page size: 1, page 1
[Employee (2, Sam, 28)]
Page size: 2, page 0
[Employee (5, Satish, 30), Employee (2, Sam, 28)]
Page size: 2, page 1
[Employee (7, Rimi, 30), Employee (4, Richard, 32)]

9. CRUD Operations using XML Configured Context

We will modify the context so that the repositories can be scanned. We take care of below points in the XML context.

  1. If you want to initialize a database and you can provide a reference to a DataSource bean, use the initialize-database tag in the spring-jdbc namespace.
  2. Repositories are scanned using <jpa:repositories.
  3. In order to use <jpa:repositories> element,  we need to add JPA namespace to the XML. We will use <context:annotation-config /> to point to the main configuration class.
  4. Define entityManagerFactory
  5. Define transactionManager

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:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.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">

	<jpa:repositories base-package="com.javacodegeeks.spring.repositories" />

	<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="packagesToScan" value="com.javacodegeeks.spring.jpa" />
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="database" value="HSQL" />
				<property name="generateDdl" value="true" />
			</bean>
		</property>
	</bean>

	<jdbc:initialize-database data-source="dataSource">
		<jdbc:script location="classpath:data.sql" />
	</jdbc:initialize-database>

	<jdbc:embedded-database id="dataSource" type="HSQL" />

	<context:annotation-config />
	<bean id="mainBean"
		class="com.javacodegeeks.spring.jpa.SpringDataJpaExampleUsingXML" />

</beans>

Create the XML context using ClassPathXmlApplicationContext. Remaining code related to CRUD operations remain same.

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

SpringDataJpaExampleUsingXML:

package com.javacodegeeks.spring.jpa;

import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.stereotype.Repository;

import com.javacodegeeks.spring.repositories.EmployeeRepository;


@Configuration
@Repository
public class SpringDataJpaExampleUsingXML {
	@Autowired
	private EmployeeRepository repository;
	
	@Autowired
	private DataSource dataSource;

	public static void main(String[] args) throws URISyntaxException, Exception {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		try {
			SpringDataJpaExampleUsingXML s = (SpringDataJpaExampleUsingXML) ctx.getBean("mainBean");
			System.out.println("Add employees");
			s.addEmployees();
			System.out.println("Find all employees");
			s.findAllEmployees();
			System.out.println("Find employee by name 'Joe'");
			s.findEmployee("Joe");
			System.out.println("Find employee by name 'John'");
			s.findEmployee("John");
			System.out.println("Find employees by age");
			s.findEmployeesByAge(32);
			System.out.println("Find employees between 30 and 45");
			s.findEmployeesBetweenAge(30, 45);
			System.out.println("Find employees greater than 20");
			s.findEmployeesGreaterThanAgePageWise(20, 1, 0);
			s.findEmployeesGreaterThanAgePageWise(20, 1, 1);
			s.findEmployeesGreaterThanAgePageWise(20, 2, 0);
			s.findEmployeesGreaterThanAgePageWise(20, 2, 1);
		} finally {
			ctx.close();
		}
	}

	public void addEmployees() {
		Employee emp1 = new Employee("Richard", 32);
		Employee emp2 = new Employee("Satish", 30);
		Employee emp3 = new Employee("Priya", 16);
		Employee emp4 = new Employee("Rimi", 30);
		
		repository.save(emp1);
		repository.save(emp2);
		repository.save(emp3);
		repository.save(emp4);
	}

	public void findAllEmployees() {
		repository.findAll().forEach(System.out::println);
	}

	public void findEmployee(String name) {
		List<Employee> empList = repository.findEmployeesByName(name);
		System.out.println("Employee list: " + empList);
	}

	public void findEmployeesByAge(int age) {
		List<Employee> empList = repository.findEmployeesByAge(age);
		System.out.println("Employee list: " + empList);
	}
	
	public void findEmployeesBetweenAge(int from, int to) {
		List<Employee> empList = repository.findEmployeesBetweenAge(from, to);
		System.out.println("Employee list: " + empList);
	}
	
	public void populateDatabase() throws SQLException {

		ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
		populator.addScript(new ClassPathResource("data.sql"));

		Connection connection = null;

		try {
			connection = DataSourceUtils.getConnection(dataSource);
			populator.populate(connection);
		} finally {
			if (connection != null) {
				DataSourceUtils.releaseConnection(connection, dataSource);
			}
		}
	}
	
	public void findEmployeesGreaterThanAgePageWise(int age, int pageSize, int pageNbr) {
		System.out.println("Page size: " + pageSize + ", page " + pageNbr);
		Pageable pageable = new PageRequest(pageNbr, pageSize, Direction.DESC, "name", "age");
		Page<Employee> page = repository.findEmployeesByAgeGreaterThan(age, pageable);
		System.out.println(page.getContent());
	}
}

Output:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Jan 27, 2016 9:44:21 AM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
	name: default
	...]
Jan 27, 2016 9:44:21 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.10.Final}
Jan 27, 2016 9:44:21 AM org.hibernate.cfg.Environment 
INFO: HHH000206: hibernate.properties not found
Jan 27, 2016 9:44:21 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jan 27, 2016 9:44:21 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager 
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Jan 27, 2016 9:44:21 AM org.hibernate.dialect.Dialect 
INFO: HHH000400: Using dialect: org.hibernate.dialect.HSQLDialect
Jan 27, 2016 9:44:22 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory 
INFO: HHH000397: Using ASTQueryTranslatorFactory
Jan 27, 2016 9:44:22 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Jan 27, 2016 9:44:22 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Jan 27, 2016 9:44:22 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
Jan 27, 2016 9:44:22 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: Employee
Jan 27, 2016 9:44:22 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: Employee
Jan 27, 2016 9:44:22 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: Employee
Jan 27, 2016 9:44:22 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Add employees
Find all employees
Employee (1, Joe, 32)
Employee (2, Sam, 28)
Employee (3, John, 43)
Employee (4, Richard, 32)
Employee (5, Satish, 30)
Employee (6, Priya, 16)
Employee (7, Rimi, 30)
Find employee by name 'Joe'
Employee list: [Employee (1, Joe, 32)]
Find employee by name 'John'
Employee list: [Employee (3, John, 43)]
Find employees by age
Employee list: [Employee (1, Joe, 32), Employee (4, Richard, 32)]
Find employees between 30 and 45
Employee list: [Employee (1, Joe, 32), Employee (3, John, 43), Employee (4, Richard, 32), Employee (5, Satish, 30), Employee (7, Rimi, 30)]
Find employees greater than 20
Page size: 1, page 0
[Employee (5, Satish, 30)]
Page size: 1, page 1
[Employee (2, Sam, 28)]
Page size: 2, page 0
[Employee (5, Satish, 30), Employee (2, Sam, 28)]
Page size: 2, page 1
[Employee (7, Rimi, 30), Employee (4, Richard, 32)]

10. Download the Eclipse Project

This was an example about Spring Data Jpa.

Download
You can download the full source code of this example here: springDataJpaExample.zip
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of