首页 > Hibernate返回值和关闭session的矛盾

Hibernate返回值和关闭session的矛盾

在使用hibernate的时候,写一个很基础的方法,通过传入的参数获得一条或者多条记录并且把得到的model类或者List作为返回值。
可是这里遇到一个矛盾。
如果我在return之前执行session.close(),那么获得的对象就会变成空。
但是return之后方法就退出了,又无法close session了。小白一个,想知道一般的做法是怎样的,谢谢!
目前的方法是下面这样,没有关闭session。

@SuppressWarnings("unchecked")
    @Override
    public List<Idea> getIdeasInfo(int industryId, int startIndex, int count) {
        // TODO Auto-generated method stub
        String queryStr = "from Idea where industry= " + industryId
                + " and (buyerid=0 or buyerid is null) and ifOpen=0 order by posttime DESC";
        // System.out.println(queryStr);
        Query query = getSessionFactory().openSession().createQuery(queryStr);
        query.setMaxResults(count);
        query.setFirstResult(startIndex);
        List<Idea> IdeasInfo = query.list();
        return IdeasInfo;
    }

return new ArrayList<Idea>(list);

复制这个list,从而触发整个list的加载。

Update: 另一方法 Hibernate.initialize(list);


openSessionInView +1

OpenSessionInView

【热门文章】
【热门文章】