Spring Data JPA progressive learning - how to customize the query method?

Work together to create and grow together! This is the 28th day of my participation in the "Nuggets Daily New Plan · August Update Challenge", click to view the event details

1 Define the configuration and usage of the query method

In Spring Data JPA, CRUD can be implemented directly by method name

Implement CRUD by method name

If we want to implement CRUD through method names, we need to make our UserRepisitoryinheritance CrudRepository, as shown below

public interface UserRepository extends CrudRepository<UserInfo,Integer> {

}
复制代码

Then you can call UserRepositorythe method in the service layer

image.png

Selective exposure to CRUD methods

Sometimes we don't want all the methods to be exposed, when some data just want to be viewed but not modified.

The specific operation is to inherit the Repository class and write your own methods.

public interface UserRepository extends Repository<UserInfo,Integer> {
    UserInfo findOne();
    List<UserInfo> findAll();
}
复制代码

At this time controller, if you call it, there are only these two methods.

image.png

2 Method Query Policy Settings

Through @EnableJpaRepositoriesthe query strategy of the configurable method, this generally does not change, the default is fine.

@EnableJpaRepositories(queryLookupStrategy = QueryLookupStrategy.Key.CREATE_IF_NOT_FOUND)
复制代码

QueryLookupStrategy.KeyThere are three values ​​that can be selected here

Create

Create creates directly based on the method name, if UserInfo findByAgeAndName();it deletes findBycharacters, then parses Age, And, Name. If the method name does not conform to the rules, an error will be reported. In this strategy mode, it is useless to configure @Query, only the method name will be parsed.

USE_DECLARED_QUERY

It is created in a declarative way. In this strategy mode, Query must be configured, as shown below, and the method name will not be parsed.

@Query("select u from UserInfo u")
UserInfo getAllList();
复制代码

CREATE_IF_NOT_FOUND

This is a combination of the above two cases. It will be created by declarative method first. If not, the method name will be parsed to create a query. If both are not satisfied, the startup will report an error. This is the default query strategy .

3 Defining the syntax of the query method

The method name with the query function has 查询策略+查询字段+一些限制性条件clear semantics and complete functions. The following table is a list of keywords commonly used in DMQ syntax.

20191122172557317.png

Let me give you an example or two to illustrate.

//去重,and的用法
List<UserInfo> findDistinctByAddressAndName();

//根据name查找,并根据ID进行逆序排列
List<UserInfo> findByNameOrderByIdDesc();
复制代码

Although all tables start with find, JPA also supports read, get, query, stream, count, exist, delete, remove and other prefixes, which can be used literally.

4 Type-specific parameters: Sort and Pageable

To support sorting and paging, JPA supports two special types of parameters, Sort and Pageable.

Sort can achieve dynamic sorting when querying, and determines the direction of field sorting. Pageable can achieve the dual effect of paging and sorting.

Interface definition method and description:

1 Pagination and total

Page<UserInfo> findByName(String name, Pageable pageable);
复制代码

This return will contain the total number of elements and pages available, this will execute a count statement by default, so the performance is low.

2 pagination

Slice<UserInfo> findByName(String name, Pageable pageable);
复制代码

The returned result is Slice, only the query result does not care about the total number.

3 Sort

List<UserInfo> findByName(String name, Sort sort);
复制代码

You can do this when you only need to sort by adding a Sort parameter.

4 Sorting and paging

List<UserInfo> findByName(String name, Pageable pageable);
复制代码

In this case, only the results of the restricted query will be returned, and other information will not be returned.

When used in the service layer, you can do the following

//查询name是Luke的第一页,每页10个信息,并返回一共有多少页
Page<UserInfo> userList = userRepository.findByName("Luke",PageRequest.of(1,10));
//查询name是Luke的第一页的10条数据
Slice<UserInfo> userList = userRepository.findByName("Luke",PageRequest.of(1,10));
//查询name是Luke的数据,并按照age的逆序排列
List<UserInfo> userList = userRepository.findByName("Luke",new Sort(Sort.Direction.DESC,"age"));
//查询name是Luke的数据,取第一页的10条数据,并按照age的逆序排列
List<UserInfo> userList = userRepository.findByName("Luke",PageRequest.of(1,10,Sort.Direction.DESC,"age"));
复制代码

5 Limit query results: Fist and Top

When you only want to get the data of the previous days, you can use the First and Top keywords.

for example

//按照name字段顺序排列,取第一个值
UserInfo findFirstByOrderByNameAsc();
//根据Id逆序排列并取第一个值
UserInfo findTopByOrderByIdDesc();
//排序后取前10个
List<UserInfo> findFirst10ByAge(Integer age,Sort sort);
复制代码

It is worth noting that:

  • When querying, you can use numbers after top and first to indicate how many values ​​are needed.
  • If there is no number, the default is 1
  • If it is a Pageable parameter, the number after Top and First shall prevail
  • Distinct keyword is also supported

6 @NotNull @NonNullApi和@Nullable

@NotNull

Used for non-null parameters or return values

@NonNullApi

Can be defined on the package to indicate that the default behavior of the return value is not to accept null values

@Nullable

For nullable parameters or return values

The following code indicates that both the parameter and the return value can be empty.

@Nullable
UserInfo findByName(@Nullable String name);
复制代码

Guess you like

Origin juejin.im/post/7136566779282718751