Spring Data JPA教程, 第四部分: JPA Criteria Queries(未翻译)
The third part of my Spring Data JPA tutorialdescribed how you can create custom queries by using query methods. This blog entry will describe how you can implement more advanced queries by using the JPA criteria API.
If you have read the previous part of this tutorial, you might remember that the search function which I used as an example returned all persons whose last name matched with the given search criteria. This requirement is now replaced with a new one:
- The search function must return only such persons whose last name begins with the given search term.
I am going to walk you through the implementation of this requirement next.
Required Steps
The steps required to implement the new search function are following:
- Creating the JPA criteria query.
- Extending the repository to support JPA criteria queries.
- Using the created criteria query and repository.
Each of these steps is described with more details in following.
Building the JPA Criteria Query
Spring Data JPA uses the specification pattern for providing an API which is used to create queries with the JPA criteria API. The heart of this API is the Specification interface which contains a single method called toPredicate(). In order to build the required criteria query, you must create a new implementation of the Specification interface and build the predicate in thetoPredicate() method.
Before going in to the details, I will introduce the source code of my static meta model classwhich is used to create type safe queries with the JPA criteria API. The source code of thePerson_ class is given in following:
import javax.persistence.metamodel.StaticMetamodel;
/**
* A meta model class used to create type safe queries from person
* information.
* @author Petri Kainulainen
*/
@StaticMetamodel(Person.class)
public class Person_ {
public static volatile SingularAttribute<Person, String> lastName;
}
A clean way to create specifications is to implement a specification builder class and use static methods to build the actual specification instances. My specification builder class is calledPersonSpecifications and its source code given in following:
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
/**
* A class which is used to create Specification objects which are used
* to create JPA criteria queries for person information.
* @author Petri Kainulainen
*/
public class PersonSpecifications {
/**
* Creates a specification used to find persons whose last name begins with
* the given search term. This search is case insensitive.
* @param searchTerm
* @return
*/
public static Specification<Person> lastNameIsLike(final String searchTerm) {
return new Specification<Person>() {
@Override
public Predicate toPredicate(Root<Person> personRoot, CriteriaQuery<?> query, CriteriaBuilder cb) {
String likePattern = getLikePattern(searchTerm);
return cb.like(cb.lower(personRoot.<String>get(Person_.lastName)), likePattern);
}
private String getLikePattern(final String searchTerm) {
StringBuilder pattern = new StringBuilder();
pattern.append(searchTerm.toLowerCase());
pattern.append("%");
return pattern.toString();
}
};
}
}
Testing my specification builder implementation is pretty straightforward. I used Mockito mocking framework to mock the JPA criteria API. The source code of my test class is given following:
import org.junit.Test;
import org.springframework.data.jpa.domain.Specification;
import javax.persistence.criteria.*;
import static junit.framework.Assert.assertEquals;
import static org.mockito.Mockito.*;
public class PersonSpecificationsTest {
private static final String SEARCH_TERM = "Foo";
private static final String SEARCH_TERM_LIKE_PATTERN = "foo%";
private CriteriaBuilder criteriaBuilderMock;
private CriteriaQuery criteriaQueryMock;
private Root<Person> personRootMock;
@Before
public void setUp() {
criteriaBuilderMock = mock(CriteriaBuilder.class);
criteriaQueryMock = mock(CriteriaQuery.class);
personRootMock = mock(Root.class);
}
@Test
public void lastNameIsLike() {
Path lastNamePathMock = mock(Path.class);
when(personRootMock.get(Person_.lastName)).thenReturn(lastNamePathMock);
Expression lastNameToLowerExpressionMock = mock(Expression.class);
when(criteriaBuilderMock.lower(lastNamePathMock)).thenReturn(lastNameToLowerExpressionMock);
Predicate lastNameIsLikePredicateMock = mock(Predicate.class);
when(criteriaBuilderMock.like(lastNameToLowerExpressionMock, SEARCH_TERM_LIKE_PATTERN)).thenReturn(lastNameIsLikePredicateMock);
Specification<Person> actual = PersonSpecifications.lastNameIsLike(SEARCH_TERM);
Predicate actualPredicate = actual.toPredicate(personRootMock, criteriaQueryMock, criteriaBuilderMock);
verify(personRootMock, times(1)).get(Person_.lastName);
verifyNoMoreInteractions(personRootMock);
verify(criteriaBuilderMock, times(1)).lower(lastNamePathMock);
verify(criteriaBuilderMock, times(1)).like(lastNameToLowerExpressionMock, SEARCH_TERM_LIKE_PATTERN);
verifyNoMoreInteractions(criteriaBuilderMock);
verifyZeroInteractions(criteriaQueryMock, lastNamePathMock, lastNameIsLikePredicateMock);
assertEquals(lastNameIsLikePredicateMock, actualPredicate);
}
}
However, if you have to build more complex queries by using this approach, testing your queries will become more troublesome because the JPA criteria API is not the easiest one to mock. In this case it is a good idea to divide the search conditions into multiple specifications and use theSpecifications class to combine your specification instances. This way your unit tests don’t become so complex but you can still harness the power of the JPA criteria API in your application.
Extending the Repository
Extending your Spring Data JPA repository to support JPA criteria queries is quite easy. All you have to do is to extend the JpaSpecificationExecutor interface. This gives you access to thefindAll(Specification spec) method which returns all entities fulfilling the search conditions specified by the specification. The source code of my PersonRepository is given in following:
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* Specifies methods used to obtain and modify person related information
* which is stored in the database.
* @author Petri Kainulainen
*/
public interface PersonRepository extends JpaRepository<Person, Long>, JpaSpecificationExecutor<Person> {
}
Using the Specification Builder and the Repository
The last step is to implement the service class which uses the created specification builder and the repository. The search() method of the PersonService interface takes the used search term as a parameter. The relevant part of the PersonService interface is given in following:
* Declares methods used to obtain and modify person information.
* @author Petri Kainulainen
*/
public interface PersonService {
/**
* Searches persons by using the given search term as a parameter.
* @param searchTerm
* @return A list of persons whose last name begins with the given search term. If no persons is found, this method
* returns an empty list. This search is case insensitive.
*/
public List<Person> search(String searchTerm);
}
The implementation of the search() method is very simple. It simply passes the search term to the lastNameIsLike() method of the PersonSpecifications class and gives the created specification object to the PersonRepository. The source code of the implementation of the search() method is given in following:
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
* This implementation of the PersonService interface communicates with
* the database by using a Spring Data JPA repository.
* @author Petri Kainulainen
*/
@Service
public class RepositoryPersonService implements PersonService {
private static final Logger LOGGER = LoggerFactory.getLogger(RepositoryPersonService.class);
@Resource
private PersonRepository personRepository;
@Transactional(readOnly = true)
@Override
public List<Person> search(String searchTerm) {
LOGGER.debug("Searching persons with search term: " + searchTerm);
//Passes the specification created by PersonSpecifications class to the repository.
return personRepository.findAll(lastNameIsLike(searchTerm));
}
}
This solution is not perfect from the architectural point of view because it introduces a dependency between the service layer and the Spring Data JPA. A general guideline is that an upper layer should not have any knowledge about the implementation details of the layers located below it.
One solution to this problem would be to create a custom search method and integrate it with the generic repository abstraction as described in the reference manual of Spring Data JPA. However, this would mean that you would have to write a lot of boilerplate code which does not really add any value to your application. Also, since the goal of the Spring Data JPA is to reduce the amount of boilerplate code, I think that my solution is an acceptable compromise between over engineering and getting things done in a clean way.
Oh, this reminds me of something. We should not forget the unit test of the search() method. The source code of this unit test is given in following:
import org.junit.Test;
import org.springframework.data.jpa.domain.Specification;
import static junit.framework.Assert.assertEquals;
import static org.mockito.Mockito.*;
public class RepositoryPersonServiceTest {
private static final String SEARCH_TERM = "foo";
private RepositoryPersonService personService;
private PersonRepository personRepositoryMock;
@Before
public void setUp() {
personService = new RepositoryPersonService();
personRepositoryMock = mock(PersonRepository.class);
personService.setPersonRepository(personRepositoryMock);
}
@Test
public void search() {
List<Person> expected = new ArrayList<Person>();
when(personRepositoryMock.findAll(any(Specification.class))).thenReturn(expected);
List<Person> actual = personService.search(SEARCH_TERM);
verify(personRepositoryMock, times(1)).findAll(any(Specification.class));
verifyNoMoreInteractions(personRepositoryMock);
assertEquals(expected, actual);
}
}
What is Next?
I have now demonstrated to you how you can use the JPA criteria API with Spring Data JPA. As always, the example application of this blog entry is available at Github. The next part of my Spring Data JPA tutorial describes how you can use Querydsl for building queries with Spring Data JPA.
Spring Data JPA教程, 第四部分: JPA Criteria Queries(未翻译)的更多相关文章
- Spring Data Solr教程(翻译) 开源的搜索服务器
Solr是一个使用开源的搜索服务器,它采用Lucene Core的索引和搜索功能构建,它可以用于几乎所有的编程语言实现可扩展的搜索引擎. Solr的虽然有很多优点,建立开发环境是不是其中之一.此博客条 ...
- Spring Data Solr教程(翻译)
大多数应用都必须具有某种搜索功能,问题是搜索功能往往是巨大的资源消耗并且它们由于沉重的数据库加载而拖垮你的应用的性能 这就是为什么转移负载到一个外部的搜索服务器是一个不错的主意,Apache Solr ...
- spring cloud系列教程第四篇-Eureka基础知识
通过前三篇文章学习,我们搭建好了两个微服务工程.即:order80和payment8001这两个服务.有了这两个基础的框架之后,我们将要开始往里面添加东西了.还记得分布式架构的几个维度吗?我们要通过一 ...
- Spring入门详细教程(四)
前言 本篇紧接着spring入门详细教程(三),建议阅读本篇前,先阅读第一篇,第二篇以及第三篇.链接如下: Spring入门详细教程(一) https://www.cnblogs.com/jichi/ ...
- Spring Boot2 系列教程 (十四) | 统一异常处理
如题,今天介绍 SpringBoot 是如何统一处理全局异常的.SpringBoot 中的全局异常处理主要起作用的两个注解是 @ControllerAdvice 和 @ExceptionHandler ...
- Spring Boot2 系列教程(十四)CORS 解决跨域问题
今天和小伙伴们来聊一聊通过CORS解决跨域问题. 同源策略 很多人对跨域有一种误解,以为这是前端的事,和后端没关系,其实不是这样的,说到跨域,就不得不说说浏览器的同源策略. 同源策略是由 Netsca ...
- Spring Boot系列教程十四:Spring boot同时支持HTTP和HTTPS
自签证书 openssl生成服务端证书,不使用CA证书直接生成 -in server.csr -signkey server.key -out server.crt # 5.server证书转换成ke ...
- Spring Cloud Stream教程(四)消费群体
虽然发布订阅模型可以轻松地通过共享主题连接应用程序,但通过创建给定应用程序的多个实例来扩展的能力同样重要.当这样做时,应用程序的不同实例被放置在竞争的消费者关系中,其中只有一个实例预期处理给定消息. ...
- Spring Cloud Config教程(四)快速开始
Spring Cloud Config为分布式系统中的外部配置提供服务器和客户端支持.使用Config Server,您可以在所有环境中管理应用程序的外部属性.客户端和服务器上的概念映射与Spring ...
随机推荐
- acdream B - 郭式树 (水题 卡cin,cout, 卡LL)
题目 输入正好是long long的最大, 但是答案超long long 所以用unsigned, 不能用cin cout否则一定超时: 不能用abs(), abs 只用于整数. unsigned ...
- Oracle 数据库整理表碎片
Oracle 数据库整理表碎片 转载:http://kyle.xlau.org/posts/table-fragmentation.html 表碎片的来源 当针对一个表的删除操作很多时,表会产生大量碎 ...
- [swustoj 771] 奶牛农场
奶牛农场 Description 将军有一个用栅栏围成的矩形农场和一只奶牛,在农场的一个角落放有一只矩形的箱子,有一天将军要出门,他就把奶牛用一根绳子套牢,然后将绳子的另一端绑到了那个箱子不靠栅栏的角 ...
- HDU 4607 Park Visit (DP最长链)
[题目]题意:N个城市形成一棵树,相邻城市之间的距离是1,问访问K个城市的最短路程是多少,共有M次询问(1 <= N, M <= 100000, 1 <= K <= N). [ ...
- POJ 1523 SPF (割点,连通分量)
题意:给出一个网络(不一定连通),求所有的割点,以及割点可以切分出多少个连通分量. 思路:很多种情况. (1)如果给的图已经不是连通图,直接“ No SPF nodes”. (2)求所有割点应该不难 ...
- Iwpriv工作流程及常用命令使用
iwpriv工具通过ioctl动态获取相应无线网卡驱动的private_args所有扩展参数 iwpriv是处理下面的wlan_private_args的所有扩展命令,iwpriv的实现上,是这样的, ...
- Hadoop集群中Hbase的介绍、安装、使用
导读 HBase – Hadoop Database,是一个高可靠性.高性能.面向列.可伸缩的分布式存储系统,利用HBase技术可在廉价PC Server上搭建起大规模结构化存储集群. 一.Hbase ...
- Handling HTTP 404 Error in ASP.NET Web API
Introduction: Building modern HTTP/RESTful/RPC services has become very easy with the new AS ...
- [CODEVS1697]⑨要写信
题目描述 Description 琪露诺(冰之妖精)有操控冷气的能力.能瞬间冻结小东西,比普通的妖精更危险.一直在释放冷气的她周围总是非常寒冷. 由于以下三点原因…… 琪露诺的符卡 冰符“Icicle ...
- C语言反转字符串
也是面腾讯的一道编程题=,= 这题比较简单 代码如下: #include <stdio.h> #include <string.h> // 非递归实现字符串反转 char *r ...