一.集成Spring+SpringDataJpa
步骤:
1.导入Spring+SpringMVC+SpringDataJpa集成3大框架需要的jar包
2.配置applicationContext.xml文件
①配置连接池:4大属性、连接、线程
②集成hibernate的jpa功能:扫描实体类包、配置JPA实现(四大金刚)
③Jpa 事务配置:声明注解支持
④SpringDataJpa配置:扫描的repository包
3.准备Domain
①抽取父类: BaseDomain,类上加注解@MappedSuperclass(不持久化到表)
②准备子类实体类,类上加注解@Entity、@Table(name="表名")
4.准备Repository
①功能接口继承JpaRepository<1,2> 参数1:实体类名、参数2:实体类主键类型
5.测试集成
①测试类上加注解@RunWith(SpringJUnit4ClassRunner.class)、@ContextConfiguration("classpath:applicationContext.xml")
②方法上加上注解@Autowired注入功能对象
③使用功能对象通过调用父类方法测试CRUD功能
6.SpringDataJpa了解
①七个Repository接口
②两大Repository实现类
③打开SimpleJpaRepository.java,单击鼠标右键show diagrams查看结构图
7.SpringDataJpa分页排序功能
①创建page对象:Pageable pageable = new PageRequest(0, 10);//0就是第一页,每页10条数据
②创建排序对象:Sort sort = new Sort(Sort.Direction.DESC,"字段");//排序规则、排序字段
③排序与分页集成:Pageable pageable = new PageRequest(0, 10,sort);
8.SpringDataJpa条件查询
按照java驼峰式书写规范加一些特定关键字
9.@Query注解查询
只需要将@Query("jpql语句")定义在Respository的方法之上即可,nativeQuery = true:支持使用原生sql语句
10.JpaSpecificationExecutor了解
JpaSpecificationExecutor(JPA规则执行者)是JPA2.0提供的Criteria API的使用封装,可以用于动态生成Query来满足我们业务中的各种复杂场景
11.JpaSpecificationExecutor的使用
①使我们的接口去继承JpaSpecificationExecutor<实体类名>接口
②创建Specification spec = new Specification<Employee>()对象
③覆写toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb)方法,返回查询条件对象
12.jpa-spec插件功能介绍及使用
①功能:减少重复代码
②使用:在Maven中引入相应的包
<dependency>
<groupId>com.github.wenhao</groupId>
<artifactId>jpa-spec</artifactId>
<version>3.1.1</version>
<!-- 把所有依赖都过滤 -->
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
③语法:Specification<Employee> spec = Specifications.<Employee>and().like("排序字段", "%条件%").build()
13.Query查询条件
①BaseQuery:抽取公共的查询条件
②一个实体类对应一个查询条件类
③创建Specification的流程放到Query里