目录
ORMHibernate,JPA和SpringDataJpaJPA入门案列JPA的API介绍getOne和findOne的比较JPQL的基本使用
specification的基本使用 ★example的基本使用
多表设计
表之间的划分 分析步骤 多表设计(一对多) 多表设计(一对多) 对象导航查询
specification的使用
Specification是一个函数式接口,需要实现toPredicate(Root root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder)方法
root:查询的根对象(查询的任何属性都可以从根对象中获取)CriteriaQuery:顶层查询对象,自定义查询方式(了解:一般不用)CriteriaBuilder:查询的构造器,封装了很多的查询条件
单参数查询
@Test
public void testSpecificationOneParam(){
Specification
<Customer> specification
=(root
,query
,cb
)->{
Path
<Object> custName
= root
.get("custName");
Predicate predicate
= cb
.equal(custName
, "飞飞飞");
return predicate
;
};
List
<Customer> customers
= this.customerRepository
.findAll(specification
);
customers
.forEach((customer
-> System
.out
.println(customer
)));
}
多参数查询
@Test
public void testSpecificationMoreParam(){
Specification
<Customer> specification
=(root
, query
, criteriaBuilder
) -> {
Path
<Object> custName
= root
.get("custName");
Path
<Object> custIndustry
= root
.get("custIndustry");
Predicate preName
= criteriaBuilder
.equal(custName
, "飞飞飞");
Predicate preIndy
= criteriaBuilder
.equal(custIndustry
, "娱乐");
Predicate predicate
= criteriaBuilder
.and(preName
, preIndy
);
return predicate
;
};
List
<Customer> customers
= this.customerRepository
.findAll(specification
);
customers
.forEach((customer
)-> System
.out
.println(customer
));
}
模糊查询
@Test
public void testSpecificationLike(){
Specification
<Customer> specification
=(root
, query
, criteriaBuilder
) -> {
Path
<Object> custName
= root
.get("custName");
Predicate predicate
= criteriaBuilder
.like(custName
.as(String
.class), "%飞__");
return predicate
;
};
List
<Customer> customers
= this.customerRepository
.findAll(specification
);
customers
.forEach(customer
-> System
.out
.println(customer
));
}
分页查询
@Test
public void testSpecificationPage(){
int row
=5;
int page
=0;
Specification
<Customer> specification
=(root
, query
, criteriaBuilder
) -> {
Path
<Object> custName
= root
.get("custName");
Predicate predicate
= criteriaBuilder
.like(custName
.as(String
.class), "%飞__");
return predicate
;
};
Pageable pageable
=PageRequest
.of(page
,row
,Sort
.Direction
.ASC
,"custId");
Page
<Customer> cpage
= this.customerRepository
.findAll(pageable
);
List
<Customer> customers
= cpage
.getContent();
int totalPages
= cpage
.getTotalPages();
long totalElements
= cpage
.getTotalElements();
System
.out
.println("数据总页数:"+totalPages
);
System
.out
.println("数据总条数:"+totalElements
);
customers
.forEach(customer
-> System
.out
.println(customer
));
}
输出