**Java SpringDataJpa**
一.SpringDataJpaSpringData -> SpringDataJpa:操作数据库变得更好简单1.pom.xml配置- 1.基本的SSJ的导入 - 2.SpringDataJpa
org.springframework.data
spring-data-jpa
${spring-data-jpa.version}
2.SpringDataJpa基本配置
1.配置对应的Spring-data-jpa<jpa:repositories base-package=“cn.itsource.aisell.repository”
entity-manager-factory-ref=“entityManagerFactory”
transaction-manager-ref=“transactionManager”
></jpa:repositories>2.继承JpaRepository interface EmployeeRepository extends JpaRepository<Employee,Long>, JpaSpecificationExecutor
3.完成相应的CRUDemployeeRepository.findAll();
employeeRepository.findOne(Long id);
employeeRepository.save(对象); //添加或者修改
employeeRepository.delete(id/对象);
employeeRepository.findAll(Pageable) -> 分页
Pageable pageable = new PageRequest(0, 5); //0就是第一页
employeeRepository.findAll(Sort) -> 排序
Sort sort = new Sort(Sort.Direction.DESC,“username”);
如果要把分页和排序结合起来: new PageRequest(0, 5,sort);3.高级查询1.名称规则
findByUsername(String username) -> 根据名称查询 username = ?
findByUsernameLike(String username) -> username like ?
findByUsernameLikeAndEmailLike(String username,String email) -> username like ? and email like ?
详细规则请看文件(idea也有提示)
2.Query注解
@Query(“jpql的语句”)
@Query(“select o from Employee o where o.name like ?1”)
//@Query(“select o from Employee o where o.name like :name”)
@Query(nativeQuery = true,value=“select * from employee”)二.高级查询与分页1.JpaSpecificationExecutor可以不写SQL也能够完成功能1.我们的Repository继承JpaSpecificationExecutor
EmployeeRepository extends JpaRepository<Employee,Long>,
JpaSpecificationExecutor
2.findAll的查询方法
employeeRepository.findAll(Specification spec)
employeeRepository.findAll(Specification spec,Pageable pageable)
new Specification{
//root:(根,表)获取字段
//query:where,group by ,order by…
//cb: 条件判断(一个或者多个)
@Override
public Predicate toPredicate(Root root,
CriteriaQuery<?> query,
CriteriaBuilder cb) {
Path path = root.get(“username”);//拿到要做查询的字段
Predicate p = cb.like(path, “%1%”);//like代表做模糊查询,后面就是它的条件值
return p;
}
}2.jpa-spec
com.github.wenhao
jpa-spec
3.1.0
//第一个参数: true -> 条件过滤启用
//第二个参数: 需要过滤的属性
//第三个参数: 过滤条件的 ?对应的值
Specification specification = Specifications.and()
.eq(StringUtils.isNotBlank(request.getName()), “name”, name)
.gt(Objects.nonNull(request.getAge()), “age”, 18)
.build();3.Query的抽取Query作用:接收前台传过来的查询条件(分页,数据)
BaseQuery:公共的查询【规范,公共的代码】
int currentPage=1;
getJpaPage{return currentPage-1}
int pageSize=10;
String orderName;
Boolean orderType=true;
提供getter,setter方法
//规定子类必需提供一个拿到条件的方法
protected abstract Specification createSpec();
//提供获取排序的方法
Sort createSort(){
//1.如果orderName没有值,就返回null【不排序】
//2.如果orderType是DESC,就升级(反之就降序)
}
EmployeeQuery:Employee单独的查询
username,email,age,…
Specification createSpec(){…}