首页 > Web开发 > 详细

Hibernate Dao操作总结

时间:2022-05-27 22:13:09      阅读:6      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!