ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

SpringDataJpa:JpaRepository增删改查

2022-03-05 06:31:08  阅读:173  来源: 互联网

标签:SpringDataJpa name 改查 entity entities JpaRepository 查询 where String


Jpa查询

1. JpaRepository简单查询

基本查询也分为两种,一种是spring data默认已经实现,一种是根据查询的方法来自动解析成SQL。

  • 预先生成方法

spring data jpa 默认预先生成了一些基本的CURD的方法,例如:增、删、改等等

继承JpaRepository

  1. public interface UserRepository extends JpaRepository<User, Long> {
  2. }
  • 使用默认方法

  1. @Test
  2. public void testBaseQuery() throws Exception {
  3. User user=new User();
  4. userRepository.findAll();
  5. userRepository.findOne(1l);
  6. userRepository.save(user);
  7. userRepository.delete(user);
  8. userRepository.count();
  9. userRepository.exists(1l);
  10. // ...
  11. }
  • 自定义的简单查询就是根据方法名来自动生成SQL,主要的语法是findXXBy,readAXXBy,queryXXBy,countXXBygetXXBy后面跟属性名称:
  • 具体的关键字,使用方法和生产成SQL如下表所示
KeywordSampleJPQL snippet
AndfindByLastnameAndFirstname… where x.lastname = ?1 and x.firstname = ?2
OrfindByLastnameOrFirstname… where x.lastname = ?1 or x.firstname = ?2
Is,EqualsfindByFirstnameIs,findByFirstnameEquals… where x.firstname = ?1
BetweenfindByStartDateBetween… where x.startDate between ?1 and ?2
LessThanfindByAgeLessThan… where x.age < ?1
LessThanEqualfindByAgeLessThanEqual… where x.age ⇐ ?1
GreaterThanfindByAgeGreaterThan… where x.age > ?1
GreaterThanEqualfindByAgeGreaterThanEqual… where x.age >= ?1
AfterfindByStartDateAfter… where x.startDate > ?1
BeforefindByStartDateBefore… where x.startDate < ?1
IsNullfindByAgeIsNull… where x.age is null
IsNotNull,NotNullfindByAge(Is)NotNull… where x.age not null
LikefindByFirstnameLike… where x.firstname like ?1
NotLikefindByFirstnameNotLike… where x.firstname not like ?1
StartingWithfindByFirstnameStartingWith… where x.firstname like ?1 (parameter bound with appended %)
EndingWithfindByFirstnameEndingWith… where x.firstname like ?1 (parameter bound with prepended %)
ContainingfindByFirstnameContaining… where x.firstname like ?1 (parameter bound wrapped in %)
OrderByfindByAgeOrderByLastnameDesc… where x.age = ?1 order by x.lastname desc
NotfindByLastnameNot… where x.lastname <> ?1
InfindByAgeIn(Collection ages)… where x.age in ?1
NotInfindByAgeNotIn(Collection age)… where x.age not in ?1
TRUEfindByActiveTrue()… where x.active = true
FALSEfindByActiveFalse()… where x.active = false
IgnoreCasefindByFirstnameIgnoreCase… where UPPER(x.firstame) = UPPER(?1)

按照Spring Data的规范,查询方法以find | read | get 开头,涉及查询条件时,条件的属性条件关键字连接,

要注意的是条件属性以首字母大写

  • 示例:

例如:定义一个Entity实体类:

  1. class People{
  2. private String firstName;
  3. private String lastName;
  4. }

以上使用and条件查询时,应这样写:

findByLastNameAndFirstName(String lastName,String firstName);

注意:条件的属性名称与个数要与参数的位置与个数一一对应

 

2.JpaRepository查询方法解析流程

JPA方法名解析流程

  • Spring Data JPA框架在进行方法名解析时,会先把方法名多余的前缀截取掉
  • 比如find、findBy、read、readBy、get、getBy,然后对剩下部分进行解析。
  • 假如创建如下的查询: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()"。


特殊的参数(分页或排序):

  • 还可以直接在方法的参数上加入分页或排序的参数,比如:
  1. Page<UserModel> findByName(String name, Pageable pageable);
  2. List<UserModel> findByName(String name, Sort sort);
  • Pageable 是spring封装的分页实现类,使用的时候需要传入页数、每页条数和排序规则
  1. @Test
  2. public void testPageQuery() throws Exception {
  3. int page=1,size=10;
  4. Sort sort = new Sort(Direction.DESC, "id");
  5. Pageable pageable = new PageRequest(page, size, sort);
  6. userRepository.findALL(pageable);
  7. userRepository.findByUserName("testName", pageable);
  8. }

使用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,如果有,那么就不会按照接口定义的方法来解析。

使用@Query来指定本地查询

只要设置nativeQuery为true

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

注意:当前版本的本地查询不支持翻页和动态的排序

使用命名化参数

使用@Param即可

比如:

  1. @Query(value="select o from UserModel o where o.name like %:nn")
  2. public List<UserModel> findByUuidOrAge(@Param("nn") String name);

创建查询的顺序

  • 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个元素,或者支取前一个实体。
  1. User findFirstByOrderByLastnameAsc();
  2. User findTopByOrderByAgeDesc();
  3. Page<User> queryFirst10ByLastname(String lastname, Pageable pageable);
  4. List<User> findFirst10ByLastname(String lastname, Sort sort);
  5. List<User> findTop10ByLastname(String lastname, Pageable pageable);

4.JpaRepository多表查询

  • 多表查询在spring data jpa中有两种实现方式,第一种是利用hibernate的级联查询来实现,第二种是创建一个结果集的接口来接收连表查询后的结果,这里主要第二种方式。
  • 首先需要定义一个结果集的接口类
  1. public interface HotelSummary {
  2. City getCity();
  3. String getName();
  4. Double getAverageRating();
  5. default Integer getAverageRatingRounded() {
  6. return getAverageRating() == null ? null : (int) Math.round(getAverageRating());
  7. }
  8. }
  • 查询的方法返回类型设置为新创建的接口
  1. @Query("select h.city as city, h.name as name, avg(r.rating) as averageRating "
  2. + "from Hotel h left outer join h.reviews r where h.city = ?1 group by h")
  3. Page<HotelSummary> findByCity(City city, Pageable pageable);
  4. @Query("select h.name as name, avg(r.rating) as averageRating "
  5. + "from Hotel h left outer join h.reviews r group by h")
  6. Page<HotelSummary> findByCity(Pageable pageable);
  • 使用
  1. Page<HotelSummary> hotels = this.hotelRepository.findByCity(new PageRequest(0, 10, Direction.ASC, "name"));
  2. for(HotelSummary summay:hotels){
  3. System.out.println("Name" +summay.getName());
  4. }

在运行中Spring会给接口(HotelSummary)自动生产一个代理类来接收返回的结果,代码汇总使用getXX的形式来获取

 

JPA更新

支持更新类的Query语句

添加@Modifying即可

  • 比如:
  1. @Modifying
  2. @Query(value="update UserModel o set o.name=:newName where o.name like %:nn")
  3. public int findByUuidOrAge(@Param("nn") String name,@Param("newName") String newName);

注意:

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

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

JPA删除

 

SQL方式-删除

  1. @Query(value = "delete from r_upa where user_id= ?1 and point_indecs_id in (?2)", nativeQuery = true)
  2. @Modifying
  3. void deleteByUserAndPointIndecs(Long uid, List<Long> hids);

注意:

执行delete和update语句一样,需要添加@Modifying注解,使用时在Repository或者更上层需要@Transactional注解。

函数(delete)方式-删除

  • 直接可以使用delete(id),依据id来删除一条数据
  • 也可以使用deleteByName(String name)时,需要添加@Transactional注解,才能使用
  • Spring Data JPA的deleteByXXXX,是先select,在整个Transaction完了之后才执行delete

 JpaRepository

  1. @NoRepositoryBean
  2. public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
  3. /**
  4. * Deletes the given entities in a batch which means it will create a single {@link Query}. Assume that we will clear
  5. * the {@link javax.persistence.EntityManager} after the call.
  6. *
  7. * @param entities
  8. * 批量解绑多个,优势:只会形成一个SQL语句
  9. */
  10. void deleteInBatch(Iterable<T> entities);
  11. /**
  12. * Deletes all entities in a batch call.
  13. */
  14. void deleteAllInBatch();
  15. }

CrudRepository

  1. @NoRepositoryBean
  2. public interface CrudRepository<T, ID> extends Repository<T, ID> {
  3. /**
  4. * Deletes the entity with the given id.
  5. *
  6. * @param id must not be {@literal null}.
  7. * @throws IllegalArgumentException in case the given {@code id} is {@literal null}
  8. */
  9. void deleteById(ID id);
  10. /**
  11. * Deletes a given entity.
  12. *
  13. * @param entity
  14. * @throws IllegalArgumentException in case the given entity is {@literal null}.
  15. */
  16. void delete(T entity);
  17. /**
  18. * Deletes the given entities.
  19. *
  20. * @param entities
  21. * @throws IllegalArgumentException in case the given {@link Iterable} is {@literal null}.
  22. */
  23. void deleteAll(Iterable<? extends T> entities);
  24. /**
  25. * Deletes all entities managed by the repository.
  26. */
  27. void deleteAll();
  28. }

 

JPA添加

利用JpaRepository和CrudRepository中的 save操作

JpaRepository

  1. @NoRepositoryBean
  2. public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
  3. /*
  4. * (non-Javadoc)
  5. * @see org.springframework.data.repository.CrudRepository#save(java.lang.Iterable)
  6. */
  7. <S extends T> List<S> saveAll(Iterable<S> entities);
  8. /**
  9. * Flushes all pending changes to the database.
  10. */
  11. void flush();
  12. /**
  13. * Saves an entity and flushes changes instantly.
  14. *
  15. * @param entity
  16. * @return the saved entity
  17. */
  18. <S extends T> S saveAndFlush(S entity);
  19. }

CrudRepository

  1. @NoRepositoryBean
  2. public interface CrudRepository<T, ID> extends Repository<T, ID> {
  3. /**
  4. * Saves a given entity. Use the returned instance for further operations as the save operation might have changed the
  5. * entity instance completely.
  6. *
  7. * @param entity must not be {@literal null}.
  8. * @return the saved entity will never be {@literal null}.
  9. */
  10. <S extends T> S save(S entity);
  11. /**
  12. * Saves all given entities.
  13. *
  14. * @param entities must not be {@literal null}.
  15. * @return the saved entities will never be {@literal null}.
  16. * @throws IllegalArgumentException in case the given entity is {@literal null}.
  17. */
  18. <S extends T> Iterable<S> saveAll(Iterable<S> entities);
  19. }

JpaRepository和CrudRepository 的区别

  • JpaRepository 中的save方法实现源码:
  1. @Transactional
  2. public <S extends T> List<S> save(Iterable<S> entities) {
  3. List<S> result = new ArrayList<S>();
  4. if (entities == null) {
  5. return result;
  6. }
  7. for (S entity : entities) {
  8. result.add(save(entity));
  9. }
  10. return result;
  11. }
  • CrudRepository 中的save方法源代码
  1. @Transactional
  2. public <S extends T> S save(S entity) {
  3. if (entityInformation.isNew(entity)) {
  4. em.persist(entity);//是新的就插入
  5. return entity;
  6. } else {
  7. return em.merge(entity); //不是新的merge
  8. }
  9. }

由源码可知CrudRepository 中的save方法是相当于merge+save ,它会先判断记录是否存在,如果存在则更新,不存在则插入记录

 

转载来源:https://blog.csdn.net/fly910905/article/details/78557110

标签:SpringDataJpa,name,改查,entity,entities,JpaRepository,查询,where,String
来源: https://www.cnblogs.com/dusucyy/p/15966908.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有