Spring Data Jpa Guide

Spring Data JPA, part of the larger Spring Data family, makes it easy to easily implement JPA based repositories. This module deals with enhanced support for JPA based data access layers. It makes it easier to build Spring-powered applications that use data access technologies.

Implementing a data access layer of an application has been cumbersome for quite a while. Too much boilerplate code has to be written to execute simple queries as well as perform pagination, and auditing. Spring Data JPA aims to significantly improve the implementation of data access layers by reducing the effort to the amount that’s actually needed. As a developer you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically.

https://spring.io/projects/spring-data-jpa

Query Methods

Spring Data Jpa 名词: Query Creation <==> Query Methods

Spring Data Jpa Query Creation

这一部分主要是 Jpa 通过对查询方法的解析->转换成sql语句进行查询,避免了编写sql的过程.

example:

interface PersonRepository extends Repository<Person, Long> {
    // select person from person whre lastname=?1
  List<Person> findByLastname(String lastname);
}

Modifying Queries

Spring Data Jpa Modifying Queries

修改数据

@Modifying
@Query("update User u set u.firstname = ?1 where u.lastname = ?2")
int setFixedFirstnameFor(String firstname, String lastname);

删除数据

interface UserRepository extends Repository<User, Long> {

  void deleteByRoleId(long roleId);

  @Modifying
  @Query("delete from User u where user.role.id = ?1")
  void deleteInBulkByRoleId(long roleId);
}

注意事项 Jpa中除了查询都需要加@Transactional 事务

Using JPA Named Queries

使用JpaName查询

Example

public interface UserRepository extends JpaRepository<User, Long> {

  List<User> findByLastname(String lastname);

  User findByEmailAddress(String emailAddress);
}

Using @Query

Using named queries to declare queries for entities is a valid approach and works fine for a small number of queries. As the queries themselves are tied to the Java method that executes them, you can actually bind them directly by using the Spring Data JPA @Query annotation rather than annotating them to the domain class. This frees the domain class from persistence specific information and co-locates the query to the repository interface.

Example:

public interface UserRepository extends JpaRepository<User, Long> {

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

NativeQuery=true

public interface UserRepository extends JpaRepository<User, Long> {

  @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);
}

Applying Query Hints

To apply JPA query hints to the queries declared in your repository interface, you can use the @QueryHints annotation. It takes an array of JPA @QueryHint annotations plus a boolean flag to potentially disable the hints applied to the additional count query triggered when applying pagination, as shown in the following example:

Example

public interface UserRepository extends Repository<User, Long> {

  @QueryHints(value = { @QueryHint(name = "name", value = "value")},
              forCounting = false)
  Page<User> findByLastname(String lastname, Pageable pageable);
}

Query To Dto

Example:

@Query(value = "select new com.park.carTrace.pojo.CarTraceResult(a.plateNo, a.plateColor, a.typeName, a.parkName, max(a.time), count(a.id)) " +
            " from CarTraceRecordEntity a where a.plateNo = ?1 and a.plateColor = ?2 " +
            "and a.type = ?3 group by a.parkNo order by time desc ")
    List<CarTraceResult> queryCarTraceRecord(String plateNo, Integer plateColor, Integer type);

from cnblog

Specifications

Spring Data Jpa Using Specifications

  • 关于一些使用Specification的技巧

    如何 使用 and or 操作

       private Predicate orPredicate(CriteriaBuilder criteriaBuilder, Predicate p1, Predicate p2) {
         if (p1 == null || p2 == null) {
             return p1 == null ? p2 : p1;
         }
         return criteriaBuilder.or(p1, p2);
     }
    
  • Jpa 关联查询Specification

Spring Data Jpa Specifications Join

Query By Example

Spring Data Jap Query By Example

简单理解 @Transactional

Spring Data Jpa Transactional

Query 查询能够返回Stream ? 是不是很爽?

Spring Data Jpa Return Types

Other

  • Using Sort

Spring Data Jpa Using Sort

  • Using SpEL Expressions

Spring Data Jpa Using SpEl Expressions

Jpa 关联查询OneToMany ManyToOne

Jpa 关联查询注意事项

优雅使用关联查询

使用注意事项

主键id不能为 int类型 进行save操作时,id为0

OneToMany中的 updateable insertable注意事项

  • Jpa查询 Native 和 非 Native区别

nativeQuery = true时,是可以执行原生sql语句的。
nativeQuery = false时, 关联的是Table的表和字段

  • Jpa 返回某些字段

定义Dto 定义构造方法,查询返回即可.