Spring Data JPA

更新时间:2023-12-01 19:14:01 阅读量: 教育文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

Spring Data JPA

1. 配置

class=\ p:generateDdl=\ p:database=\

p:databasePlatform=\ p:showSql=\

class=\ p:entityManagerFactory-ref=\

2. JPA查询接口

Spring Data 提供了以下几个 Repository 接口供我们使用:

1. Repository 该接口仅仅是一个标识,表示任何继承自它的接口均为仓库接口,其本身并

未提供任何方法。

2. CrudRepository 该接口继承自 Repository ,它提供了一组 CRUD 的数据库操作方法。 3. PagingAndSortingRepository 继承自 CrudRepository ,它在 CRUD 的基础上还提供了

分页查询与排序的方法。

4. JpaRepository 继承自 PagingAndSortingRepository , 在此基础上,它提供了一组符合

JPA 规范的数据操作方法。

5. JpaSpecificationExecutor 特殊的一个接口,从名称上来看就知道其不属于 Repository

范畴,它提供了 JPA Criteria 查询的相关方法(见5.1)

数据访问接口需继承以下4个JPA接口。

1.1 Repository

标记接口,空。

1.2 CrudRepository

实现CRUD方法的接口。

public interface CrudRepository extends Repository

Methods

Modifier and Type Method and Description long

count()

Returns the number of entities available.

void

delete(ID id)

Deletes the entity with the given id.

void

delete(Iterable entities) Deletes the given entities.

void delete(T entity) Deletes a given entity.

void deleteAll()

Deletes all entities managed by the repository.

boolean exists(ID id)

Returns whether an entity with the given id exists.

Iterable findAll()

Returns all instances of the type.

Iterable findAll(Iterable ids)

Returns all instances of the type with the given IDs.

T

findOne(ID id)

Retrieves an entity by its id.

Iterable S

save(Iterable entities) Saves all given entities. save(S entity) Saves a given entity.

1.3 PagingAndSortingRepository

实现分页和排序方法的接口。

public interface PagingAndSortingRepository extends CrudRepository

Methods Modifier and Type Method and Description Page findAll(Pageable pageable) Returns a Page of entities meeting the paging restriction provided in the Pageable object. Iterable findAll(Sort sort) Returns all entities sorted by the given options.

1.4 JpaRepository

实现批量操作的接口。

public interface JpaRepository extends PagingAndSortingRepository

Methods

Modifier and Type Method and Description void

deleteAllInBatch()

Deletes all entites in a batch call.

void

deleteInBatch(Iterable entities)

Deletes the given entities in a batch which means it will create a single Query.

List List List void

findAll()

findAll(Iterable ids) findAll(Sort sort) flush()

Flushes all pending changes to the database.

List T

save(Iterable entities)

saveAndFlush(T entity)

Saves an entity and flushes changes instantly.

3. 查询方法定义

3.1 定义

直接在接口中定义查询方法,如果是符合规范的,可以不用写实现,目前支持的 关键字写法如下:

Keyword And

Sample

findByLastnameAndFirstname

JPQL snippet

… where x.lastname = ?1 and x.firstname = ?2

… where x.lastname = ?1 or x.firstname = ?2

Or findByLastnameOrFirstname findByFirstname,

Is,Equals findByFirstnameIs, findByFirstnameEquals

… where x.firstname = 1?

Between LessThan LessThanEqual GreaterThan

findByStartDateBetween findByAgeLessThan findByAgeLessThanEqual findByAgeGreaterThan

… where x.startDate between 1? and ?2 … where x.age < ?1 … where x.age <= ?1 … where x.age > ?1 … where x.age >= ?1 … where x.startDate > ?1 … where x.startDate < ?1 … where x.age is null … where x.age not null … where x.firstname like ?1 … where x.firstname not like ?1 … where x.firstname like ?1 (parameter bound with appended %)

… where x.firstname like ?1 (parameter bound with prepended %)

GreaterThanEqual findByAgeGreaterThanEqual After Before IsNull

findByStartDateAfter findByStartDateBefore findByAgeIsNull

IsNotNull,NotNull findByAge(Is)NotNull Like NotLike StartingWith

findByFirstnameLike findByFirstnameNotLike findByFirstnameStartingWith

EndingWith findByFirstnameEndingWith

Keyword Containing

Sample

findByFirstnameContaining

JPQL snippet

… where x.firstname like ?1 (parameter bound wrapped in %)

… where x.age = ?1 order by x.lastname desc

… where x.lastname <> ?1

OrderBy Not In NotIn True False IgnoreCase

findByAgeOrderByLastnameDesc findByLastnameNot

findByAgeIn(Collection ages) … where x.age in ?1 findByAgeNotIn(Collection age)

findByActiveTrue() findByActiveFalse()

findByFirstnameIgnoreCase

… where x.age not in ?1 … where x.active = true … where x.active = false

… where UPPER(x.firstame) = UPPER(?1)

附加:

public interface PersonRepository extends Repository { // Enables the distinct flag for the query

List findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname); List findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);

// Enabling ignoring case for an individual property List findByLastnameIgnoreCase(String lastname); // Enabling ignoring case for all suitable properties

List findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname);

// Enabling static ORDER BY for a query

List findByLastnameOrderByFirstnameAsc(String lastname); List findByLastnameOrderByFirstnameDesc(String lastname); }

3.2 解析

Spring Data JPA框架在进行方法名解析时,会先把方法名多余的前缀截取掉,比如 find、findBy、read、readBy、get、getBy,然后对剩下部分进行解析。

假如创建如下的查询:findByUserDepUuid(),框架在解析该方法时,首先剔除 findBy,然后对剩下的属性进行解析,假设查询实体为Doc

1:先判断 userDepUuid (根据 POJO 规范,首字母变为小写)是否为查询实体的一个

属性,如果是,则表示根据该属性进行查询;如果没有该属性,继续第二步;

2:从右往左截取第一个大写字母开头的字符串此处为Uuid),然后检查剩下的字符串是 否为查询实体的一个属性,如果是,则表示根据该属性进行查询;如果没有该属性, 则重复第二步,继续从右往左截取;最后假设user为查询实体的一个属性;

3:接着处理剩下部分(DepUuid),先判断 user 所对应的类型是否有depUuid属性,如 果有,则表示该方法最终是根据 “ Doc.user.depUuid” 的取值进行查询;否则继 续按照步骤 2 的规则从右往左截取,最终表示根据 “Doc.user.dep.uuid” 的值进 行查询。

4:可能会存在一种特殊情况,比如 Doc包含一个 user 的属性,也有一个 userDep 属 性,此时会存在混淆。可以明确在属性之间加上 \以显式表达意图,比如 \或者 \

3.3 分页

可以直接在方法的参数上加入分页或排序的参数,比如:

Page findByName(String name, Pageable pageable);

3.3.1 分页请求接口Pageable

实现类为PageRequest。

Methods

Modifier and Type Method and Description

Pageable

first()

Returns the Pageable requesting the first page.

int getOffset()

Returns the offset to be taken according to the underlying page and

page size.

int getPageNumber()

Returns the page to be returned.

int getPageSize()

Returns the number of items to be returned.

Sort

getSort()

Returns the sorting parameters.

boolean hasPrevious()

Returns whether there's a previous Pageable we can access from the current one.

Pageable

next()

Returns the Pageable requesting the next Page.

Pageable

previousOrFirst()

Returns the previous Pageable or the first Pageable if the current one already is the first one.

3.3.2 分页结果接口Page

根据分页请求,查询数据库后返回的分页结果对象。 实现类为PageImpl。 Methods

Modifier and Type Method and Description

List getContent()

Returns the page content as List.

int getNumber()

Returns the number of the current page.

int getNumberOfElements()

Returns the number of elements currently on this page.

int getSize()

Returns the size of the page.

Sort

getSort()

Returns the sorting parameters for the page.

long getTotalElements()

Returns the total amount of elements.

int getTotalPages()

Returns the number of total pages.

boolean hasContent()

Returns whether the Page has content at all.

boolean hasNextPage()

Returns if there is a next page.

boolean hasPreviousPage()

Returns if there is a previous page.

boolean isFirstPage()

Returns whether the current page is the first one.

boolean isLastPage()

Returns whether the current page is the last one.

Iterator iterator() Pageable

nextPageable()

Returns the Pageable to request the next Page.

Pageable

previousPageable()

Returns the Pageable to request the previous page.

3.4 排序

List findByName(String name, Sort sort)

排序对象Sort: Nested Classes

Modifier and Type Class and Description

static class Sort.Direction

Enumeration for sort directions.

static class Sort.Order

PropertyPath implements the pairing of an Sort.Direction and a property.

Enum Sort.Direction

public static enum Sort.Direction extends Enum

Enum Constants Enum Constant and Description ASC DESC 4. 自定义查询NamedQuery

有时候框架提供的不一定够我们使用,那么就需要我们进行自定义查询,这里使用@Query注解的形式来完成,当然也可以通过在Entry上面用@NamedQuery注解具体的sql和对应的方法。

4.1 查询

在UserDao中添加两个方法,如下:

@Query(value=\nativeQuery=true) public User findByusername(String username); @Query(\public User findByPassword(@Param(\ 第一个方法通过注解值nativeQuery=true说明这个是一个原生的sql语句查询,当然结果会自动帮我们进行转换,是不是很方便? 参数赋值:

? 可以通过?占位符,需要注意参数的位置和个数 ? 可以通过:的形式,需要@Param注解来定义

注意:

1:方法的参数个数必须和@Query里面需要的参数个数一致 2:如果是like,后面的参数需要前面或者后面加“%”,比如下面都对: @Query(\public List findByUuidOrAge(String name);

@Query(\public List findByUuidOrAge(String name);

@Query(\public List findByUuidOrAge(String name);

当然,这样在传递参数值的时候就可以不加‘%’了,当然加了也不会错

分别执行这两个方法,我们查看log信息: 1.原生查询,SQL语句与定义的相同 Hibernate: select * from

t_user u where

本文来源:https://www.bwwdw.com/article/2b2t.html

Top