1 springdatajpa
springdata是对jpa进行封装后形成一个springdatajpa的框架。封装之后,使用更加简单
1.1 SpringdataJpa 的crud
用法
定义一个接口 继承 JpaRepository这个接口
新增/修改 save:employeeRepository.save(employee)
查询 findOne:employeeRepository.findOne(id)
查询所有 findAll:employeeRepository.findAll()
删除 delete /deleteInBatch: employeeRepository.delete(id)
1.2 Springdatajpa的分页和排序
排序:Sort sort = new Sort(Sort.Direction.DESC,"age");
分页: Page<Employee> page = employeeRepository.findAll(pageable);
1.3 按照条件规则查询(只适合简单的查询)
public List<Employee> findByUsernameLike(String username);
public List<Employee> findByUsername(String username);
public List<Employee> findByAgeGreaterThan(Integer age);
1.4Query注解式jpql
@Query("select o from Employee o where o.id =(select max(p.id) from Employee p)")
public Employee queryEmployee();
1.5 JpaSpecificationExecutor 查询
JpaSpecificationExecutor:jpa提供的规范的执行者,作用可以用来动态的生成jpql语句来查询
@Test
public void testJpaSpecificationExecutorAndPage()throws Exception{
Specification specification = new Specification<Employee>(){
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
Path path1 = root.get("username");
Predicate predicate1 = criteriaBuilder.like(path1, "%1%");
Path path2 = root.get("age");
Predicate predicate2 = criteriaBuilder.greaterThan(path2, 30);
CriteriaQuery cq = criteriaQuery.where(predicate1, predicate2);
return cq.getRestriction();
}
};
Sort sort = new Sort(Sort.Direction.DESC,"age");
Pageable pageable = new PageRequest(0, 2, sort);
Page<Employee> page = employeeRepository1.findAll(specification,pageable);
List<Employee> employees = page.getContent();
for (Employee employee : employees) {
System.out.println(employee);
}
}
1.6 jpa-spe插件
jpa-spec:对JpaSpecificationExecutor 进行封装,简化jpa规则查询的写法,更好用
@Test
public void testJpaSpe()throws Exception{
Specification<Employee> specification = Specifications.<Employee>and()
.like("username", "%1%")
.gt("age", 30)
.build();
List<Employee> employees = employeeRepository1.findAll(specification);
for (Employee employee : employees) {
System.out.println(employee);
}
}
1.7完成公共抽取
public abstract Specification createSpecification();
public Sort createSort() {
if (this.getOrderByName() != null) {
String orderByType = this.getOrderByType();
Sort.Direction type = "DESC".equals(orderByType) ? Sort.Direction.DESC : Sort.Direction.ASC;
return new Sort(type, this.getOrderByName());
}else{
return null;
}
}