Spring Data using JPA as an example
Introduction
Spring Data makes it easier to create Spring-driven applications that use new ways of accessing data, such as non-relational databases, map-reduce frameworks, cloud services, as well as the already well-improved support for relational databases.
This article will cover one of Spring Data’s sub-projects - JPA
What can Spring Data - JPA
- Creating and maintaining repositories created using Spring and JPA
- Support for QueryDSL and JPA queries
- Domain Class Audit
- Support for batch loading, sorting, dynamic queries
- XML mapping support for entities
Why you might need Spring Data - JPA
I would answer this way - if you need to quickly create a Repository layer based on JPA in the project, intended mainly for CRUD operations, and you do not want to create abstract DAOs, their implementation interfaces, then Spring Data - JPA is a good choice.
Where to begin
Let's assume you already have a maven project with Spring connected, a database configured by EntityManager.
1. Add artifact with Spring Data - JPA
org.springframework.data spring-data-jpa 1.0.2.RELEASE
2. In your applicationContext.xml you need to add the path where your Repository interfaces will be stored
3. Create an Entity and Repository Interface for It
package com.test.entity;
...
@Entity
public class Test {
@Id
@GeneratedValue (strategy = GenerationType.AUTO)
@Column (name = "id")
private long id;
private boolean dummy;
private int tries;
...
}
package com.test.repository;
import org.springframework.data.repository.CrudRepository;
import com.test.entity.Test;
public interface TestRepository extends CrudRepository {} 4. Now you can use the created interface in your application
public class TestServiceImpl extends TestService {
@Autowired
TestRepository testRepository;
...
}Inheriting from CrudRepository you got the opportunity to call methods such as:
- save
- findOne
- exists
- findAll
- count
- delete
- deleteAll
without the need to implement their implementation.
Work with requests, sorting, portion loading
Consider an example: you need to make a query that selects all Test records whose dummy field is set to false and the records are sorted by the tries field in ABC order.
To solve this problem, you can choose one of several options:
Option 1:
@Query ("FROM Test where dummy =? 1 ORDER BY tries ASC")
List findTests (boolean dummyVal);
, or option 2:
ListfindByDummyOrderByTriesAsc (boolean dummyVal);
If with the first method everything is extremely simple and this is a familiar query, then the second method is to make up the name of the method, in a special way I use keywords such as: “find”, “order”, name of variables, etc. Spring Data - JPA developers have tried to take into account most of the possible options that you may need.
Specification and CriteriaBuilder
If you need to write a really complex query for this, you can use Specification.
An example in which, depending on the "retries", data with different "dummy" values will be selected.
public final class TestSpecs {
public static specification checkRetries (final int retries) {
return new specification() {
@Override
public Predicate toPredicate (Rootroot, CriteriaQuery query, CriteriaBuilder cb) {
if (retries> 10) {
return cb.equal (root.get ("dummy"), false);
} else {
return cb.equal (root.get ("dummy"), true);
}
}
};
}
}
The following example will show how you can use the created Specification to filter all data.
Extend your interface with JpaSpecificationExecutor
public interface TestRepository extends CrudRepository, JpaSpecificationExecutor {}
and call the findAll method passing it the created Specification
public class TestServiceImpl extends TestService {
@Autowired
TestRepository testRepository;
public void doTest () {
int retries = 5;
List result = testRepository.findAll (Specifications.where (TestSpecs.checkRetries (retries))
...
}
}
Documentation
The main project site with a list of all Spring Data subprojects .
Spring Data Project Site - JPA
Technical Documentation with Examples of All Features