Hibernate Dao操作总结

Hibernate

  1. 使用构建器:

    //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();
    
  2. 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()
    
  3. 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();

Hibernate Dao操作总结

原文:https://www.cnblogs.com/gronbu1/p/15339740.html

以上是Hibernate Dao操作总结的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>