Spring Data JPA
更新时间:2023-12-01 19:14:01 阅读量: 教育文库 文档下载
- spring是什么意思推荐度:
- 相关推荐
Spring Data JPA
1. 配置
class=\ p:generateDdl=\ p:database=\ p:databasePlatform=\ p:showSql=\ class=\ p:entityManagerFactory-ref=\ 2. JPA查询接口 Spring Data 提供了以下几个 Repository 接口供我们使用: 1. Repository 该接口仅仅是一个标识,表示任何继承自它的接口均为仓库接口,其本身并 未提供任何方法。 2. CrudRepository 该接口继承自 Repository ,它提供了一组 CRUD 的数据库操作方法。 3. PagingAndSortingRepository 继承自 CrudRepository ,它在 CRUD 的基础上还提供了 分页查询与排序的方法。 4. JpaRepository 继承自 PagingAndSortingRepository , 在此基础上,它提供了一组符合 JPA 规范的数据操作方法。 5. JpaSpecificationExecutor 特殊的一个接口,从名称上来看就知道其不属于 Repository 范畴,它提供了 JPA Criteria 查询的相关方法(见5.1) 数据访问接口需继承以下4个JPA接口。 1.1 Repository 标记接口,空。 1.2 CrudRepository 实现CRUD方法的接口。 public interface CrudRepository Methods Modifier and Type Method and Description long count() Returns the number of entities available. void delete(ID id) Deletes the entity with the given id. void delete(Iterable extends T> entities) Deletes the given entities. void delete(T entity) Deletes a given entity. void deleteAll() Deletes all entities managed by the repository. boolean exists(ID id) Returns whether an entity with the given id exists. Iterable Returns all instances of the type. Iterable Returns all instances of the type with the given IDs. T findOne(ID id) Retrieves an entity by its id. save(Iterable 1.3 PagingAndSortingRepository 实现分页和排序方法的接口。 public interface PagingAndSortingRepository Methods Modifier and Type Method and Description Page 1.4 JpaRepository 实现批量操作的接口。 public interface JpaRepository Methods Modifier and Type Method and Description void deleteAllInBatch() Deletes all entites in a batch call. void deleteInBatch(Iterable Deletes the given entities in a batch which means it will create a single Query. List findAll() findAll(Iterable Flushes all pending changes to the database. save(Iterable saveAndFlush(T entity) Saves an entity and flushes changes instantly. 3. 查询方法定义 3.1 定义 直接在接口中定义查询方法,如果是符合规范的,可以不用写实现,目前支持的 关键字写法如下: Keyword And Sample findByLastnameAndFirstname JPQL snippet … where x.lastname = ?1 and x.firstname = ?2 … where x.lastname = ?1 or x.firstname = ?2 Or findByLastnameOrFirstname findByFirstname, Is,Equals findByFirstnameIs, findByFirstnameEquals … where x.firstname = 1? Between LessThan LessThanEqual GreaterThan findByStartDateBetween findByAgeLessThan findByAgeLessThanEqual findByAgeGreaterThan … where x.startDate between 1? and ?2 … where x.age < ?1 … where x.age <= ?1 … where x.age > ?1 … where x.age >= ?1 … where x.startDate > ?1 … where x.startDate < ?1 … where x.age is null … where x.age not null … where x.firstname like ?1 … where x.firstname not like ?1 … where x.firstname like ?1 (parameter bound with appended %) … where x.firstname like ?1 (parameter bound with prepended %) GreaterThanEqual findByAgeGreaterThanEqual After Before IsNull findByStartDateAfter findByStartDateBefore findByAgeIsNull IsNotNull,NotNull findByAge(Is)NotNull Like NotLike StartingWith findByFirstnameLike findByFirstnameNotLike findByFirstnameStartingWith EndingWith findByFirstnameEndingWith Keyword Containing Sample findByFirstnameContaining JPQL snippet … where x.firstname like ?1 (parameter bound wrapped in %) … where x.age = ?1 order by x.lastname desc … where x.lastname <> ?1 OrderBy Not In NotIn True False IgnoreCase findByAgeOrderByLastnameDesc findByLastnameNot findByAgeIn(Collection ages) … where x.age in ?1 findByAgeNotIn(Collection age) findByActiveTrue() findByActiveFalse() findByFirstnameIgnoreCase … where x.age not in ?1 … where x.active = true … where x.active = false … where UPPER(x.firstame) = UPPER(?1) 附加: public interface PersonRepository extends Repository List // Enabling ignoring case for an individual property List List // Enabling static ORDER BY for a query List 3.2 解析 Spring Data JPA框架在进行方法名解析时,会先把方法名多余的前缀截取掉,比如 find、findBy、read、readBy、get、getBy,然后对剩下部分进行解析。 假如创建如下的查询:findByUserDepUuid(),框架在解析该方法时,首先剔除 findBy,然后对剩下的属性进行解析,假设查询实体为Doc 1:先判断 userDepUuid (根据 POJO 规范,首字母变为小写)是否为查询实体的一个 属性,如果是,则表示根据该属性进行查询;如果没有该属性,继续第二步; 2:从右往左截取第一个大写字母开头的字符串此处为Uuid),然后检查剩下的字符串是 否为查询实体的一个属性,如果是,则表示根据该属性进行查询;如果没有该属性, 则重复第二步,继续从右往左截取;最后假设user为查询实体的一个属性; 3:接着处理剩下部分(DepUuid),先判断 user 所对应的类型是否有depUuid属性,如 果有,则表示该方法最终是根据 “ Doc.user.depUuid” 的取值进行查询;否则继 续按照步骤 2 的规则从右往左截取,最终表示根据 “Doc.user.dep.uuid” 的值进 行查询。 4:可能会存在一种特殊情况,比如 Doc包含一个 user 的属性,也有一个 userDep 属 性,此时会存在混淆。可以明确在属性之间加上 \以显式表达意图,比如 \或者 \ 3.3 分页 可以直接在方法的参数上加入分页或排序的参数,比如: Page 3.3.1 分页请求接口Pageable 实现类为PageRequest。 Methods Modifier and Type Method and Description Pageable first() Returns the Pageable requesting the first page. int getOffset() Returns the offset to be taken according to the underlying page and page size. int getPageNumber() Returns the page to be returned. int getPageSize() Returns the number of items to be returned. Sort getSort() Returns the sorting parameters. boolean hasPrevious() Returns whether there's a previous Pageable we can access from the current one. Pageable next() Returns the Pageable requesting the next Page. Pageable previousOrFirst() Returns the previous Pageable or the first Pageable if the current one already is the first one. 3.3.2 分页结果接口Page 根据分页请求,查询数据库后返回的分页结果对象。 实现类为PageImpl。 Methods Modifier and Type Method and Description List Returns the page content as List. int getNumber() Returns the number of the current page. int getNumberOfElements() Returns the number of elements currently on this page. int getSize() Returns the size of the page. Sort getSort() Returns the sorting parameters for the page. long getTotalElements() Returns the total amount of elements. int getTotalPages() Returns the number of total pages. boolean hasContent() Returns whether the Page has content at all. boolean hasNextPage() Returns if there is a next page. boolean hasPreviousPage() Returns if there is a previous page. boolean isFirstPage() Returns whether the current page is the first one. boolean isLastPage() Returns whether the current page is the last one. Iterator nextPageable() Returns the Pageable to request the next Page. Pageable previousPageable() Returns the Pageable to request the previous page. 3.4 排序 List 排序对象Sort: Nested Classes Modifier and Type Class and Description static class Sort.Direction Enumeration for sort directions. static class Sort.Order PropertyPath implements the pairing of an Sort.Direction and a property. Enum Sort.Direction public static enum Sort.Direction extends Enum Enum Constants Enum Constant and Description ASC DESC 4. 自定义查询NamedQuery 有时候框架提供的不一定够我们使用,那么就需要我们进行自定义查询,这里使用@Query注解的形式来完成,当然也可以通过在Entry上面用@NamedQuery注解具体的sql和对应的方法。 4.1 查询 在UserDao中添加两个方法,如下: @Query(value=\nativeQuery=true) public User findByusername(String username); @Query(\public User findByPassword(@Param(\ 第一个方法通过注解值nativeQuery=true说明这个是一个原生的sql语句查询,当然结果会自动帮我们进行转换,是不是很方便? 参数赋值: ? 可以通过?占位符,需要注意参数的位置和个数 ? 可以通过:的形式,需要@Param注解来定义 注意: 1:方法的参数个数必须和@Query里面需要的参数个数一致 2:如果是like,后面的参数需要前面或者后面加“%”,比如下面都对: @Query(\public List @Query(\public List @Query(\public List 当然,这样在传递参数值的时候就可以不加‘%’了,当然加了也不会错 分别执行这两个方法,我们查看log信息: 1.原生查询,SQL语句与定义的相同 Hibernate: select * from t_user u where Iterable S entities) Saves all given entities. save(S entity) Saves a given entity. List T entities)
正在阅读:
Spring Data JPA12-01
2019年我爱冬天作文500字06-12
行为矫正技术资料整理11-25
《一夜的工作》教学设计411-23
多离子水技术05-02
猴宝宝起名字 精选50个经典创意好名字05-02
梳理《史记》素材,为作文添彩09-15
0-06长大汽车理论大题04-28
企业并购习题12-10
禅语05-02
- exercise2
- 铅锌矿详查地质设计 - 图文
- 厨余垃圾、餐厨垃圾堆肥系统设计方案
- 陈明珠开题报告
- 化工原理精选例题
- 政府形象宣传册营销案例
- 小学一至三年级语文阅读专项练习题
- 2014.民诉 期末考试 复习题
- 巅峰智业 - 做好顶层设计对建设城市的重要意义
- (三起)冀教版三年级英语上册Unit4 Lesson24练习题及答案
- 2017年实心轮胎现状及发展趋势分析(目录)
- 基于GIS的农用地定级技术研究定稿
- 2017-2022年中国医疗保健市场调查与市场前景预测报告(目录) - 图文
- 作业
- OFDM技术仿真(MATLAB代码) - 图文
- Android工程师笔试题及答案
- 生命密码联合密码
- 空间地上权若干法律问题探究
- 江苏学业水平测试《机械基础》模拟试题
- 选课走班实施方案
- Spring
- Data
- JPA
- 上海市奉贤区2017届高三上学期期末质量抽测(一模)数学(含答案)word版
- 2019届高考英语语言点综合练习及简析12
- 我的体育锻炼历程与感悟
- 252kV HGIS液压机构 - 图文
- 河道景观监理大纲
- 参加全市组工干部培训班学习心得体会九-精选模板
- 大数据--学习笔记
- 关于引进、激励优秀人才管理办法
- 论张岱《陶庵梦忆》中四大审美意象
- 16秋天大《运筹学》在线作业一 辅导资料
- 计算机2017年江苏跨地区单招一轮联考试卷
- SysView成功案例 - 图文
- 黄岗梁国家森林公园导游词
- 行业细分龙头
- 烟草局稽查员工作总结
- 局解 第一章 头颈部复习题
- 广东海洋大学 - 计算机科学与技术 - 数据库实验4
- 《西游记》填空100题
- 苏教版一年级数学下册第三单元《认识100以内的数》教案
- 课标实验版必修3《启蒙运动》word教案