SpringDataJpa——JpaRepository增删改查 1. JpaRepository简单查询 基本查询也分为两种,一种是spring data默认已经实现,一种是根据查询的方法来自动解析成SQL。 预先生成方法 spring data jpa 默认预先生成了一些基本的CURD的方法,例如:增、删、改等等 继承JpaRepository public interface UserRepository extends JpaRepository<User, Long> { } @Test public void testBaseQuery() throws Exception { User user=new User(); userRepository.findAll(); userRepository.findOne(1l); userRepository.save(user); userRepository.delete(user); userRepository.count(); userRepository.exists(1l); // ... } 自定义的简单查询就是根据方法名来自动生成SQL,主要的语法是findXXBy,readAXXBy,queryXXBy,countXXBy, getXXBy后面跟属性名称: 具体的关键字,使用方法和生产成SQL以下表所示 Keyword Sample JPQL snippet And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2 Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2 Is,Equals findByFirstnameIs,findByFirstnameEquals … where x.firstname = ?1 Between findByStartDateBetween … where x.startDate between ?1 and ?2 LessThan findByAgeLessThan … where x.age < ?1 LessThanEqual findByAgeLessThanEqual … where x.age ⇐ ?1 GreaterThan findByAgeGreaterThan … where x.age > ?1 GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1 After findByStartDateAfter … where x.startDate > ?1 Before findByStartDateBefore … where x.startDate < ?1 IsNull findByAgeIsNull … where x.age is null IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null Like findByFirstnameLike … where x.firstname like ?1 NotLike findByFirstnameNotLike … where x.firstname not like ?1 StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %) EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %) Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %) OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc Not findByLastnameNot … where x.lastname <> ?1 In findByAgeIn(Collection ages) … where x.age in ?1 NotIn findByAgeNotIn(Collection age) … where x.age not in ?1 TRUE findByActiveTrue() … where x.active = true FALSE findByActiveFalse() … where x.active = false IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1) 按照Spring Data的规范的规范,查询方法以find | read | get 开头,涉及查询条件时,条件的属性用条件关键字链接, 要注意的是:条件属性以首字母大写。 示例: 例如:定义一个Entity实体类: class People{ private String firstName; private String lastName; } 以上使用and条件查询时,应这样写: findByLastNameAndFirstName(String lastName,String firstName); 注意:条件的属性名称与个数要与参数的位置与个数一一对应 2.JpaRepository查询方法解析流程 a.Spring Data JPA框架在进行方法名解析时,会先把方法名多余的前缀截取掉,好比find、findBy、read、readBy、get、getBy,而后对剩下部分进行解析。 b.假如建立以下的查询:findByUserDepUuid(),框架在解析该方法时,首先剔除findBy,而后对剩下的属性进行解析,假设查询实体为Doc。 -- 1.先判断userDepUuid (根据POJO(Plain Ordinary Java Object简单java对象,实际就是普通java bean)规范,首字母变为小写。)是不是查询实体的一个属性, 若是根据该属性进行查询;若是没有该属性,继续第二步。 -- 2.从右往左截取第一个大写字母开头的字符串(此处为Uuid),而后检查剩下的字符串是否为查询实体的一个属性, 若是是,则表示根据该属性进行查询;若是没有该属性,则重复第二步,继续从右往左截取;最后假设 user为查询实体的一个属性。 -- 3.接着处理剩下部分(DepUuid),先判断 user 所对应的类型是否有depUuid属性, 若是有,则表示该方法最终是根据 “ Doc.user.depUuid” 的取值进行查询; 不然继续按照步骤 2 的规则从右往左截取,最终表示根据 “Doc.user.dep.uuid” 的值进行查询。 -- 4.可能会存在一种特殊状况,好比 Doc包含一个 user 的属性,也有一个 userDep 属性,此时会存在混淆。 能够明确在属性之间加上 "_" 以显式表达意图,好比 "findByUser_DepUuid()" 或者 "findByUserDep_uuid()"。 c.特殊的参数: 还能够直接在方法的参数上加入分页或排序的参数,好比: Page<UserModel> findByName(String name, Pageable pageable); List<UserModel> findByName(String name, Sort sort); Pageable 是spring封装的分页实现类,使用的时候须要传入页数、每页条数和排序规则 @Test public void testPageQuery() throws Exception { int page=1,size=10; Sort sort = new Sort(Direction.DESC, "id"); Pageable pageable = new PageRequest(page, size, sort); userRepository.findALL(pageable); userRepository.findByUserName("testName", pageable); } d.也可使用JPA的NamedQueries,方法以下: 1:在实体类上使用@NamedQuery,示例以下: @NamedQuery(name = "UserModel.findByAge",query = "select o from UserModel o where o.age >= ?1") 2:在本身实现的DAO的Repository接口里面定义一个同名的方法,示例以下: public List<UserModel> findByAge(int age); 3:而后就可使用了,Spring会先找是否有同名的NamedQuery,若是有,那么就不会按照接口定义的方法来解析。 e.还可使用@Query来指定本地查询,只要设置nativeQuery为true,好比: @Query(value="select * from tbl_user where name like %?1" ,nativeQuery=true) public List<UserModel> findByUuidOrAge(String name); 注意:当前版本的本地查询不支持翻页和动态的排序 f.使用命名化参数,使用@Param便可,好比: @Query(value="select o from UserModel o where o.name like %:nn") public List<UserModel> findByUuidOrAge(@Param("nn") String name); g.一样支持更新类的Query语句,添加@Modifying便可,好比: @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); 注意: 1:方法的返回值应该是int,表示更新语句所影响的行数 2:在调用的地方必须加事务,没有事务不能正常执行 h.建立查询的顺序 Spring Data JPA 在为接口建立代理对象时,若是发现同时存在多种上述状况可用,它该优先采用哪一种策略呢? <jpa:repositories> 提供了query-lookup-strategy 属性,用以指定查找的顺序。它有以下三个取值: 1:create-if-not-found: 若是方法经过@Query指定了查询语句,则使用该语句实现查询; 若是没有,则查找是否认义了符合条件的命名查询,若是找到,则使用该命名查询; 若是二者都没有找到,则经过解析方法名字来建立查询。 这是querylookup-strategy 属性的默认值 2:create:经过解析方法名字来建立查询。 即便有符合的命名查询,或者方法经过@Query指定的查询语句,都将会被忽略 3:use-declared-query: 若是方法经过@Query指定了查询语句,则使用该语句实现查询; 若是没有,则查找是否认义了符合条件的命名查询,若是找到,则使用该 命名查询;若是二者都没有找到,则抛出异常 3.JpaRepository限制查询 有时候咱们只须要查询前N个元素,或者支取前一个实体。 User findFirstByOrderByLastnameAsc(); User findTopByOrderByAgeDesc(); Page<User> queryFirst10ByLastname(String lastname, Pageable pageable); List<User> findFirst10ByLastname(String lastname, Sort sort); List<User> findTop10ByLastname(String lastname, Pageable pageable); 4.多表查询 多表查询在spring data jpa中有两种实现方式,第一种是利用hibernate的级联查询来实现,第二种是建立一个结果集的接口来接收连表查询后的结果,这里主要第二种方式。 首先须要定义一个结果集的接口类。 public interface HotelSummary { City getCity(); String getName(); Double getAverageRating(); default Integer getAverageRatingRounded() { return getAverageRating() == null ? null : (int) Math.round(getAverageRating()); } } 查询的方法返回类型设置为新建立的接口 @Query("select h.city as city, h.name as name, avg(r.rating) as averageRating " + "from Hotel h left outer join h.reviews r where h.city = ?1 group by h") Page<HotelSummary> findByCity(City city, Pageable pageable); @Query("select h.name as name, avg(r.rating) as averageRating " + "from Hotel h left outer join h.reviews r group by h") Page<HotelSummary> findByCity(Pageable pageable); 使用 Page<HotelSummary> hotels = this.hotelRepository.findByCity(new PageRequest(0, 10, Direction.ASC, "name")); for(HotelSummary summay:hotels){ System.out.println("Name" +summay.getName()); } 在运行中Spring会给接口(HotelSummary)自动生产一个代理类来接收返回的结果,代码汇总使用getXX的形式来获取 参考来源:http://www.ityouknow.com/springboot/2016/08/20/springboot(%E4%BA%94)-spring-data-jpa%E7%9A%84%E4%BD%BF%E7%94%A8.html