三大框架@hibernate之JPA注解

Hibernate 三大查询方式

1.ODI查询

2.HQL查询

1
2
3
4
5
6
7
8
9
10
11
public Order findBySn(String sn) {
if (StringUtils.isEmpty(sn)) {
return null;
}
String jpql = "select orders from Order orders where lower(orders.sn) = lower(:sn)";
try {
return entityManager.createQuery(jpql, Order.class).setParameter("sn", sn).getSingleResult();
} catch (NoResultException e) {
return null;
}
}

3.QBC查询

3.1 Criteria查询

3.2 CriteriaBuilder查询

1
2

3.2.1 单一条件count

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public Long registerMemberCount(Date beginDate, Date endDate) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Member> criteriaQuery = criteriaBuilder.createQuery(Member.class);
Root<Member> root = criteriaQuery.from(Member.class);
criteriaQuery.select(root);
Predicate restrictions = criteriaBuilder.conjunction();
if (beginDate != null) {
restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("createDate"), beginDate));
}
if (endDate != null) {
restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.lessThanOrEqualTo(root.<Date>get("createDate"), endDate));
}
criteriaQuery.where(restrictions);
return super.count(criteriaQuery, null);
}

3.2.1 单一条件sum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public BigDecimal getChargePayCount(Long memberId){
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<BigDecimal> criteriaQuery = criteriaBuilder.createQuery(BigDecimal.class);
Root<Order> root = criteriaQuery.from(Order.class);
criteriaQuery.select(criteriaBuilder.sum(root.<BigDecimal> get("amount")));
Predicate restrictions = criteriaBuilder.conjunction();
if( memberId !=null){
restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.<Long>get("member"),memberId));
}
criteriaQuery.where(restrictions);
BigDecimal result = entityManager.createQuery(criteriaQuery).getSingleResult();
return result != null ? result : BigDecimal.ZERO;
}

3.2.1 多条件聚合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public Long getChargeElectricTimes(Long memberId){
Boolean isDeleted = false;
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
Root<Order> root = criteriaQuery.from(Order.class);
criteriaQuery.select(root);
Predicate restrictions = criteriaBuilder.conjunction();
if( memberId !=null){
restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.<Long>get("member"),memberId),
criteriaBuilder.equal(root.<Boolean>get("isDeleted"),isDeleted));
}
criteriaQuery.where(restrictions);
return super.count(criteriaQuery,null);
}