Hibernate
使用构建器:
//1. 获取条件构建
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
//2. 创建条件构造器
CriteriaQuery<User> cq = criteriaBuilder.createQuery(User.class);
//3. 指定根条件
Root<User> root = cq.from(User.class);
//4. 指定查询条件
List<Predicate> predicates = new ArrayList<>();
if (StringUtils.isNotEmpty(email)) {
predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("name"), name)));
}
if (StringUtils.isNotEmpty(accountId)) {
predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("sex"), sex)));
}
cq.where(predicates.toArray(new Predicate[0]));
//5. 查询数据
return getSession().createQuery(cq).getResultList();
NativeSql:
//1. 创建本地sql
String nativeSql = "select " +
"a.id,a.name,a.sex,b.num " +
"from tableA a,tableB b where a.id = b.id " +
"and a.email = :email";
//2. 创建
Query query = getSession().createNativeQuery(nativeSql, User.class);
//3. 执行
query.setParameter("email", email).getResultList()
Hsql:(可以实现使用自定义类作为数据载体)
String sql = "select new com.hytto.data.model.wear.UserDTO(pid,count(id) AS count) " +
"from User u where status = ‘a‘ and pid in (:patterns) GROUP BY email";
List<PatternReportCountDTO> list = getSession().createQuery(sql)
.setParameter("patterns", patternIdList)
.getResultList();
原文:https://www.cnblogs.com/gronbu1/p/15339740.html