zoukankan      html  css  js  c++  java
  • HibernateTemplate方法的使用

    1、查询帖子(Post)为例

    查找所有的帖子

        public List<Post> findPosts() {
            String hql = "from Post p left join fetch p.user";
            List<Post> list= null;
            list = (List<Post>) this.ht.find(hql);
            return list;
        }
        @Transactional(propagation=Propagation.REQUIRED)
        public List<Post> findPosts2() {
            List<Post> list= null;
            DetachedCriteria dc = DetachedCriteria.forClass(Post.class);
            list = (List<Post>) this.ht.findByCriteria(dc);
            return list;
        }    
        @Transactional(propagation=Propagation.REQUIRED)
        public List<Post> findPosts3() {
            List<Post> list= null;
            list = (List<Post>) this.ht.findByExample(new Post());
            return list;
        }

    特定条件查询

      @Transactional(propagation= Propagation.REQUIRED)
        public List<Post> findPostByUser(String userid) {
            String hql = "from Post p where p.user.userid = :userid";
            List<Post> list= null;
            try{
            list = (List<Post>) this.ht.findByNamedParam(hql, "userid",userid);//list = (List<Post>) this.ht.findByNamedParam(hql, new String[]{"userid"},new String[]{userid})
    }catch(Exception e){ e.printStackTrace(); } return list; }

    分页查询

        @Transactional(propagation=Propagation.REQUIRED)
        public List<Post> findPosts(int start,int limit) {
            String hql = "from Post p left join fetch p.user";
            List<Post> list= null;
            DetachedCriteria dc = DetachedCriteria.forClass(Post.class);
            list = (List<Post>) this.ht.findByCriteria(dc, start, limit);//this.ht.findByExample(new Post(), start, limit);
            return list;
        }

     原生的sql查询(返回的是object数组)

         @Transactional(propagation=Propagation.REQUIRED)
        public List<Post> findPosts4() {
            String sql = "select * from post";
            List<Post> list= null;
            list = (List<Post>) this.ht.getSessionFactory().getCurrentSession().createSQLQuery(sql).list();
            return list;
        }
            
  • 相关阅读:
    Es学习第六课, ES基本搜索_search
    Es学习第一课,了解基本功能和概念
    Es学习第二课, ES安装和客户端使用
    Es学习第四课, 倒排索引
    nginx的location配置详解
    Es学习第三课, ElasticSearch基本的增删改查
    Es学习第五课, 分词器介绍和中文分词器配置
    关于Spring的一点理解
    好久没来,回来了。
    对于ie不支持select的option的onclick事件的处理
  • 原文地址:https://www.cnblogs.com/Wen-yu-jing/p/4118505.html
Copyright © 2011-2022 走看看