Home  >  Article  >  Java  >  Introduction to application scenarios of spring data jpa (details)

Introduction to application scenarios of spring data jpa (details)

不言
不言Original
2018-09-14 16:24:583529browse

This article brings you an introduction to the application scenarios of spring data jpa (detailed). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Let’s talk briefly about the concept of JPA

: JPA (Java Persistence API) is the Java persistence specification officially proposed by Sun. It provides Java developers with an object/association mapping tool to manage relational data in Java applications.

Impact:His appearance is mainly to simplify the existing persistence development work and integrate ORM technology, ending the current Hibernate, TopLink , JDO and other ORM frameworks are operating independently

Let’s get to the point

Spring DATA JPA

 1. Concept: It is a set of JPA application framework based on ORM framework and JPA specification encapsulation, which allows developers to access and operate data with minimal code. It provides functions including addition, deletion, modification, query, etc. Commonly used functions and easy to expand! Learning and using Spring Data JPA can greatly improve development efficiency.

 2. Benefits: spring data jpa frees us from the operation of the DAO layer. Basically all CRUD can rely on it to be implemented

3. Implementation:

maven introduction:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

gradle introduction:

compile(&#39;org.springframework.boot:spring-boot-starter-data-jpa&#39;)

 Implementation: Create an interface to implement any of the following interfaces

 3.1: Repository

Overview: It is just an identifier indicating that anything that inherits it is a warehouse interface class, which is convenient for Spring to automatically scan and identify. This interface is the most basic interface. It is just an iconic interface and does not define any methods.

It is the top-level interface and an empty interface. The purpose is to unify all Repository types and enable components to be automatically recognized when scanning.

 Benefits:For example, we have some methods that we do not want to provide to the outside world. For example, we only want to provide adding and modifying methods, but not deletion methods. Then the following interfaces are If this is not possible, at this time, we can inherit this interface and then copy the corresponding methods in the CrudRepository interface to the Repository interface.

3.2: CrudRepository

Overview: Repository’s sub-interface, providing CRUD related methods

Main method:

保存
    <S extends T> S save(S entity);
批量保存
    <S extends T> Iterable<S> save(Iterable<S> entities);
根据id查询一个对象
    T findOne(ID id)
判断对象是否存在
    boolean exists(ID id)
查询所有的对象
    Iterable<T> findAll()
根据id列表查询所有的对象
    Iterable<T> findAll(Iterable<ID> ids)
计算对象的总个数
    long count()
根据id删除
    void delete(ID id)
删除对象
    void delete(T entity);
批量删除
    void delete(Iterable<? extends T> entities);
删除所有
    void deleteAll()

3.3: PagingAndSortingRepository

## Overview: CrudRepository’s sub-interface, adds a set of methods related to paging sorting

Main method:

不带分页的排序
    Iterable<T> findAll(Sort sort)
带分页的排序
    Page<T> findAll(Pageable pageable)

3.4: JpaRepository

Overview: Sub-interface of PagingAndSortingRepository, Add a set of JPA specification related methods

Main method:

查询所有对象,不排序
    List<T> findAll()
查询所有对象,并排序
    List<T> findAll(Sort sort)
批量保存
    <S extends T> List<S> save(Iterable<S> entities);
强制缓存与数据库同步
    void flush()
保存并强制同步
    T saveAndFlush(T entity)
批量删除
    void deleteInBatch(Iterable<T> entities)
删除所有
    void deleteAllInBatch();

3.5: JpaSpecificationExecutor

Overview: This is special and does not belong to the Repository system. It implements a set of JPA Criteria query-related methods, mainly an interface (auxiliary interface) used to make complex queries.

           This interface is very special and does not belong to the Repository system. Spring data JPA will not automatically scan and identify it, so it will report that the corresponding Bean cannot be found. We only need to inherit any A sub-interface that inherits Repository or directly inherits the Repository interface, Spring data JPA will automatically scan and identify it, and conduct unified management

 4. Custom method:

Prerequisite: Implement any of the above interfaces

4.1: Use @Query to create a query

 

4.1. 1: Usage

The use of @Query annotation is very simple. You only need to mark the annotation on the declared method and provide a JP QL query statement

For example:

@Query("select u from User u where u.name = :name")
User findUserByName(@Param("name") String name);

 

4.1.2:Parameter

 

4.1.2.1:Named parameter

Description: It is recommended to use this method, you can not use it Position of the tube parameter

@Query("select u from User u where u.name = :name")
User findUserByName(@Param("name") String name);

4.1.2.2: Index parameter

Description: Use ? placeholder

@Query("select u from User u where u.email = ?1")// 1表示第一个参数User findUserByEmail(String email);

4.1.2.3: SPEL expression (I just wrote it briefly here, if you are interested, you can check the documentation)

Description: Starting from Spring Data JPA version 1.4, we support the use of restricted queries through manually defined queries SpEL template expression @Query 

@Query("select u from User u where u.name = :name")
User findUserByName(@Param("name") String name);

Variables supported in SpEL-based query templates

变量
    entityName
用法
    select x from #{#entityName} x
描述
    插入entityName与给定存储库关联的域类型。该entityName解决如下:如果域类型已设置的name属性@Entity注解那么它将被使用。否则,将使用域类型的简单类名称。
注意
    该entityName可以通过自定义@Entity的注释。orm.xmlSpEL表达式不支持自定义。
    引用#entityName将会把用户类的潜在的未来重映射转换成一个不同的实体名称(例如通过使用@Entity(name = "MyUser")

 4.1.3: Classification

 

4.1.3.1: QUERY

For example:

@Query("select u from User u where u.name = :name")
User findUserByName(@Param("name") String name);

Note:

1. Use @Query to specify For local query, just set nativeQuery to true, for example:

@Query(value="select * from tbl_user where name like %?1" ,nativeQuery=true)public List<UserModel> findByUuidOrAge(String name);

2. The current version of local query does not support page turning and dynamic sorting

classification (there are also many categories in Query Query in)

  1、使用@Query在查询方法中声明查询

 @Query("select u from User u where u.emailAddress = ?1")
  User findByEmailAddress(String emailAddress);

  2、使用高级LIKE表达式

@Query("select u from User u where u.firstname like %?1")
  List<User> findByFirstnameEndsWith(String firstname);

  3、使用@Query在查询方法中声明本地计数查询以进行分页

 @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
    countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
    nativeQuery = true)
  Page<User> findByLastname(String lastname, Pageable pageable);

 4.1.3.1:修改查询

  比如:

@Modifying
@Query(value="update UserModel o set o.name=:newName where o.name like %:nn")public int findByUuidOrAge(@Param("nn") String name,@Param("newName") String newName)

  注意:可以通过使用 @Query 来执行一个更新操作,为此,我们需要在使用 @Query 的同时,* 用 @Modifying 来将该操作标识为修改查询,这样框架最终会生成一个更新的操作,而非查询操作。

  4.2:@NamedQueries创建查询

  概念:命名查询是 JPA 提供的一种将查询语句从方法体中独立出来,以供多个方法共用的功能

  用法:用户只需要按照 JPA 规范在 orm.xml 文件或者在代码中使用 @NamedQuery(或 @NamedNativeQuery)定义好查询语句,唯一要做的就是为该语句命名时,需要满足”DomainClass.methodName()”的 命名规则

  比如:

编写接口:
public interface FindUserByNamedQueryRepository extends JpaRepository<User, Integer> {
User findUserWithName(@Param("name") String name);
}
编写类:
@Entity
@NamedQueries(value={
@NamedQuery(name="User.findUserWithName",query="select u from User u where u.name = :name")
})
以下是实体类
......

  注意:

  1、@NamedQuery中的name属性的值要和接口中的方法名称一样。

  2、此处如果是多个方法,那么需要使用@NamedQueries,如果只有一个方法,则可以使用@NamedQuery,写法如下:

@NamedQuery(name="User.findUserWithName",query="select u from User u where u.name = :name")

  4.3:通过解析方法名创建查询

  概念:顾名思义,就是根据方法的名字,就能创建查询

  定义规则:

   说明:按照Spring data 定义的规则,查询方法以find|read|get开头涉及条件查询时,条件的属性用条件关键字连接,要注意的是:条件属性首字母需大写(参数名大写,条件名首字母大写,并且接口名中参数出现的顺序必须和参数列表中的参数顺序一致)

   例如:

//参数名大写,条件名首字母大写,并且接口名中参数出现的顺序必须和参数列表中的参数顺序一致
User findByNameAndEmail(String name, String email);  //相当于发送了一条SQL:select u from User u where u.name = :name and u.email = :email
  
List<User> findByNameOrPassword(String name, String password);  //相当于发送了一条SQL:select u from User u where u.name = ?1 or u.password = ?2

List<User> findByNameOrPassword(String name, String password);  //相当于发送了一条SQL:select u from User u where u.name = ?1 or u.password = ?2

List<User> findByIdBetween(Integer start, Integer end);  //相当于发送了一条SQL:select u from User u where u.id between ?1 and ?2

List<User> findByIdLessThan(Integer end);  //相当于发送了一条SQL:select u from User u where u.id < ?1
...

解析:框架在进行方法名解析时,会先把方法名多余的前缀截取掉,比如 find、findBy、read、readBy、get、getBy,然后对剩下部分进行解析。并且如果方法的最后一个参数是 Sort 或者 Pageable 类型,也会提取相关的信息,以便按规则进行排序或者分页查询。在创建查询时,我们通过在方法名中使用属性名称来表达,比如 findByIdIn()。框架在解析该方法时,首先剔除 findBy,然后对剩下的属性进行解析

一些条件查询的关键字:

框架在进行方法名解析时,会先把方法名多余的前缀截取掉,比如 find、findBy、read、readBy、get、getBy,然后对剩下部分进行解析。
并且如果方法的最后一个参数是 Sort 或者 Pageable 类型,也会提取相关的信息,以便按规则进行排序或者分页查询。在创建查询时,我们通过在方法名中使用属性名称来表达
,比如 findByIdIn()。框架在解析该方法时,首先剔除 findBy,然后对剩下的属性进行解析

And --- 等价于 SQL 中的 and 关键字,比如 findByUsernameAndPassword(String user, Striang pwd)

Or --- 等价于 SQL 中的 or 关键字,比如 findByUsernameOrAddress(String user, String addr)

Between --- 等价于 SQL 中的 between 关键字,比如 findBySalaryBetween(int max, int min)

LessThan --- 等价于 SQL 中的 "0fe0deaecdfcb2dd07d644e7e62c96a4",比如 findBySalaryGreaterThan(int min)

IsNull --- 等价于 SQL 中的 "is null",比如 findByUsernameIsNull()

IsNotNull --- 等价于 SQL 中的 "is not null",比如 findByUsernameIsNotNull()

NotNull --- 与 IsNotNull 等价

Like --- 等价于 SQL 中的 "like",比如 findByUsernameLike(String user)

NotLike --- 等价于 SQL 中的 "not like",比如 findByUsernameNotLike(String user)

OrderBy ---等价于 SQL 中的 "order by",比如 findByUsernameOrderBySalaryAsc(String user)

Not --- 等价于 SQL 中的 "! =",比如 findByUsernameNot(String user)

In --- 等价于 SQL 中的 "in",比如 findByUsernameIn(Collectionf7e83be87db5cd2d9a8a0b8117b38cd4 userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数

NotIn --- 等价于 SQL 中的 "not in",比如 findByUsernameNotIn(Collectionf7e83be87db5cd2d9a8a0b8117b38cd4 userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数

The above is the detailed content of Introduction to application scenarios of spring data jpa (details). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn