JavaEE Senior -Spring Data Study Notes

Spring Data Overview

  - Spring Data: a sub-project of the Spring. To simplify database access, support for NoSQL and relational data storage. Its main goal is to make access to the database becomes quick and easy.

  - SpringData project NoSQL storage support: MongoDB (a document database), Neo4j (graph database), Redis (key / value store), Hbase (column family databases)

  - SpringData project supported relational data storage technologies: JDBC, JPA

  - JPA Spring Data: committed to reducing the amount of development data access layer (DAO) developers only thing, just declare an interface persistence layer, the other to the Spring Data JPA to help you complete.!

  - how the framework could substitute developers to implement business logic of it? For example: When there is a UserDao.findUserById () method of such a statement, which is judged generally should be able to query the User ID according to the object satisfying the condition given condition.

   Spring Data JPA specification method name do is to determine the method name compliant What kind of logic needs to achieve.

 

Spring Data Jpa HelloWorld

  - Using Spring Data JPA persistence layer development carried out in four steps required:

    1, configure Spring JPA integration

    2, Spring Data configured in the Spring configuration file, so that Spring is the interface to create a proxy object declaration. The configuration: after <jpa repositories>, when the initialization container will scan Spring base-package package specified directory and its subdirectories

      Interface to create a proxy object to inherit the Repository or sub-interface, and registers the proxy object Spring Bean, business layer of the object can be used directly by the Spring of automatic packaging.

    3, the statement persistence layer interface that inherits Repository, Repository is a flag-type interface, it does not contain any methods, if necessary, Spring Data may be implemented Repository other sub-interface, which defines some common CRUD, and tab related methods.

    4, the required method declaration in the interface. Spring Data will be based on given policy (specific strategies explain later) to generate its implementation code.

  - set up the environment:

    1, while the download Spring Data Commons and Spring Data JPA released two packages:

      > Commons is Spring Data base package

      > And to join relevant dependent JAR files to the CLASSPATH

    2, Spring Data configured in the Spring configuration file:

      

  - Sample code:

      

 

Repository Interface Overview

  - Repository interface is a core interface Spring Data, it does not provide any way, the developer needs to define their own methods declared in the interface needs, public interface Repository <T, ID extends Serializable> {} 

  - Spring Data allows us to define only the interface, simply follow the Spring Data norms, there is no need to write the implementation class.  

   - One way and inherit Repository equivalent, is the use of @RepositoryDefinition annotation on persistence layer interface, and assign domainClass and idClass property. Two methods are completely equivalent

  - Repository sub-interfaces:

    > Based Repository provides basic data access capabilities of several of its sub-interface is extended some features. Their inheritance as follows:

      >> Repository: just a logo, indicating that any successor to its warehouses are interface classes

      >> CrudRepository: inheritance Repository, implements a set of CRUD related methods

      >> PagingAndSortingRepository: inheritance CrudRepository, to achieve a set of methods to sort the relevant page 

      >> JpaRepository: inheritance PagingAndSortingRepository, implement a set of related methods JPA specification

      >> custom XxxxRepository need to inherit JpaRepository, such XxxxRepository interface is the ability to have a common data access control layer.

      >> JpaSpecificationExecutor: Repository does not belong to the system, to achieve a set of methods JPA Criteria related to the query 

 

The method defined specification SpringData

  - simple conditional queries:

    > Simple Query Condition: query entity class or a certain set of 

    > Spring Data in accordance with specifications, query method to find | read | beginning get, when it comes to the query condition, the condition of the properties connected with the condition keyword should be noted that: condition attribute to capitalize the first letter?.

    > For example: define a class Entity Entity

         class User{

            private String firstName;

            private String lastName;

         }      

      >> And when using the connection conditions, should be written: findByLastNameAndFirstName (String lastName, String firstName);

      >> The number of the attribute names to one correspondence with the condition and position of the number of parameters 

  - Support for keyword

    > Direct query methods defined in the interface, if it is compliant, you can not write implementation currently supports keyword worded as follows:

      

      

  - Query method resolution process

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

      >> 先判断 userDepUuid (根据 POJO 规范,首字母变为小写)是否为查询实体的一个属性,如果是,则表示根据该属性进行查询;如果没有该属性,继续第二步;

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

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

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

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

      >> Page<UserModel> findByName(String name, Pageable pageable);

      >> List<UserModel> findByName(String name, Sort sort);

 

使用 @Query 注解

  - 使用@Query自定义查询

    > 这种查询可以声明在 Repository 方法中,摆脱像命名查询那样的约束,将查询直接在相应的接口方法中声明,结构更为清晰,这是 Spring data 的特有实现。

      

  - 索引参数与命名参数

    > 索引参数如下所示,索引值从1开始,查询中 ”?X” 个数需要与方法定义的参数个数相一致,并且顺序也要一致 

    > 命名参数(推荐使用这种方式):可以定义好参数名,赋值时采用@Param("参数名"),而不用管顺序。

      

    > 如果是 @Query 中有 LIKE 关键字,后面的参数需要前面或者后面加 %,这样在传递参数值的时候就可以不加 %:

      >> @Query("select o from UserModel o where o.name like ?1%")

         public List<UserModel> findByUuidOrAge(String name);

      >> @Query("select o from UserModel o where o.name like %?1")

        public List<UserModel> findByUuidOrAge(String name);

      >> @Query("select o from UserModel o where o.name like %?1%")   

        public List<UserModel> findByUuidOrAge(String name);

  - 用@Query来指定本地查询

    > 还可以使用@Query来指定本地查询,只要设置nativeQuery为true,比如:

      >> @Query(value="select * from tbl_user where name like %?1" ,nativeQuery=true)

         public List<UserModel> findByUuidOrAge(String name);

 

@Modifying 注解和事务

  - @Query 与 @Modifying 执行更新操作

    > @Query 与 @Modifying 这两个 annotation一起声明,可定义个性化更新操作,例如只涉及某些字段更新时最为常用,示例如下:

      

    > 注意:

      >> 方法的返回值应该是 int,表示更新语句所影响的行数

      >> 在调用的地方必须加事务,没有事务不能正常执行

 

事务

  - Spring Data 提供了默认的事务处理方式,即所有的查询均声明为只读事务。

  - 对于自定义的方法,如需改变 Spring Data 提供的事务默认方式,可以在方法上注解 @Transactional 声明

  - 进行多个 Repository 操作时,也应该使它们在同一个事务中处理,按照分层架构的思想,这部分属于业务逻辑层,因此,需要在 Service 层实现对多个 Repository 的调用,并在相应的方法上声明事务。

 

CrudRepository 接口

  - CrudRepository

    > CrudRepository 接口提供了最基本的对实体类的添删改查操作 :

      >> T save(T entity);//保存单个实体

      >> Iterable<T> save(Iterable<? extends T> entities);//保存集合

      >> T findOne(ID id);//根据id查找实体   

      >> boolean exists(ID id);//根据id判断实体是否存在

      >> Iterable<T> findAll();//查询所有实体,不用或慎用! 

      >> long count();//查询实体数量

      >> void delete(ID id);//根据Id删除实体   

      >> void delete(T entity);//删除一个实体

      >> void delete(Iterable<? extends T> entities);//删除一个实体的集合

      >> void deleteAll();//删除所有实体,不用或慎用! 

 

PagingAndSortingRepository接口

  - PagingAndSortingRepository

    > 该接口提供了分页与排序功能 :

      >> Iterable<T> findAll(Sort sort); //排序

      >> Page<T> findAll(Pageable pageable); //分页查询(含排序功能)

 

JpaRepository接口

  - JpaRepository

    > 该接口提供了JPA的相关功能

      >> List<T> findAll(); //查找所有实体

      >> List<T> findAll(Sort sort); //排序、查找所有实体 

      >> List<T> save(Iterable<? extends T> entities);//保存集合 

      >> void flush();//执行缓存与数据库同步 

      >> T saveAndFlush(T entity);//强制执行持久化 

      >> void deleteInBatch(Iterable<T> entities);//删除一个实体集合

 

JpaSpecificationExecutor接口

  - JpaSpecificationExecutor

    > 不属于Repository体系,实现一组 JPA Criteria 查询相关的方法

      

    > Specification:封装 JPA Criteria 查询条件。通常使用匿名内部类的方式来创建该接口的对象

 

自定义 Repository 方法

  - 为某一个 Repository 上添加自定义方法

    > 步骤:

      1、 定义一个接口: 声明要添加的, 并自实现的方法

      2、 提供该接口的实现类: 类名需在要声明的 Repository 后添加 Impl, 并实现方法

      3、 声明 Repository 接口, 并继承 1) 声明的接口

      4、 使用. 

      >>  注意: 默认情况下, Spring Data 会在 base-package 中查找 "接口名Impl" 作为实现类. 也可以通过 repository-impl-postfix 声明后缀.

  - 为所有的 Repository 都添加自实现的方法

    > 步骤:

      1、声明一个接口, 在该接口中声明需要自定义的方法, 且该接口需要继承 Spring Data 的 Repository.

      2、提供 1) 所声明的接口的实现类. 且继承 SimpleJpaRepository, 并提供方法的实现

      3、定义 JpaRepositoryFactoryBean 的实现类, 使其生成 1) 定义的接口实现类的对象

      4、修改 <jpa:repositories /> 节点的 factory-class 属性指向 3) 的全类名

      >> 注意: 全局的扩展实现类不要用 Imp 作为后缀名, 或为全局扩展接口添加 @NoRepositoryBean 注解告知  Spring Data: Spring Data 不把其作为 Repository

 

Guess you like

Origin www.cnblogs.com/LzMingYueShanPao/p/11209738.html