码迷,mamicode.com
首页 > Web开发 > 详细

HibernateTemplate方法的使用

时间:2014-11-24 15:07:27      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   使用   sp   for   

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;
    }
        

 

HibernateTemplate方法的使用

标签:style   blog   io   ar   color   os   使用   sp   for   

原文地址:http://www.cnblogs.com/Wen-yu-jing/p/4118505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!