问一个hibernate的懒加载的问题

问题描述

问一个hibernate的懒加载的问题

1.我定义Survey和Page类,Survey设置Page的集合属性,然后建立双向关联,我故意把集合注解成懒加载...
2.然后我通过这段代码把Page集合重数据库取出
3.然后调用Survey的get方法得到集合,再把Page一个一个放进集合中去
4.然后再外面迭代Survey的page集合抛异常是懒加载

为什么?为什么?为什么?

 /*
*通过survey的id取出survey
*(我用spring在这方法上面配置了事务)
*/

    public Survey findByid(int id){
        Survey survey = surveyDaoImp.getEntity(id);
        String hql = "from Page p where p.survey.id=? order by p.id desc";
        List<Page> list = pageDaoImp.findEntityByHQL(hql, id);
        for(Page page : list){
            survey.getPages().add(page);
        }
        return survey;
    }

我的测试方法

 @Test
    public void test3(){
        BeanFactory a = new ClassPathXmlApplicationContext("beans.xml");
        SurveyService s = (SurveyService) a.getBean("surveyService");
        Survey survey = s.findByid(40);
        for(Page page : survey.getPages()){
            System.out.println(page.getTitle()+":"+page.getId());
        }
    }

下面是2个javabean

 @Entity
public class Survey {
    private int id;
    private String title="未命名";
    private String preText="上一步";
    private String nextText="下一步";
    private String exitText="退出";
    private String doneText="完成";
    private Date createTime = new Date();
    private Users users;
    private List<Page> pages = new ArrayList<Page>();
    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getPreText() {
        return preText;
    }
    public void setPreText(String preText) {
        this.preText = preText;
    }
    public String getNextText() {
        return nextText;
    }
    public void setNextText(String nextText) {
        this.nextText = nextText;
    }
    public String getExitText() {
        return exitText;
    }
    public void setExitText(String exitText) {
        this.exitText = exitText;
    }
    public String getDoneText() {
        return doneText;
    }
    public void setDoneText(String doneText) {
        this.doneText = doneText;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    @ManyToOne
    @JoinColumn(name="users_id")
    public Users getUsers() {
        return users;
    }
    public void setUsers(Users users) {
        this.users = users;
    }
    @OneToMany(mappedBy="survey", cascade=CascadeType.ALL)
    public List<Page> getPages() {
        return pages;
    }
    public void setPages(List<Page> pages) {
        this.pages = pages;
    }
}

@Entity
public class Page {
    private int id;
    private String title = "未命名";
    private String description;
    private Survey survey;
    private List<Question> questions = new ArrayList<Question>();
    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    @ManyToOne
    @JoinColumn(name="survey_id")
    public Survey getSurvey() {
        return survey;
    }
    public void setSurvey(Survey survey) {
        this.survey = survey;
    }
    @OneToMany(mappedBy="page", fetch=FetchType.EAGER)
    public List<Question> getQuestions() {
        return questions;
    }
    public void setQuestions(List<Question> questions) {
        this.questions = questions;
    }
}
 **这是日志的sql语句**
Hibernate:
    select
        survey0_.id as id2_1_,
        survey0_.createTime as createTime2_1_,
        survey0_.doneText as doneText2_1_,
        survey0_.exitText as exitText2_1_,
        survey0_.nextText as nextText2_1_,
        survey0_.preText as preText2_1_,
        survey0_.title as title2_1_,
        survey0_.users_id as users8_2_1_,
    from
        Survey survey0_
    where
        survey0_.id=?
Hibernate:
    select
        page0_.id as id0_,
        page0_.description as descript2_0_,
        page0_.survey_id as survey4_0_,
        page0_.title as title0_
    from
        Page page0_
    where
        page0_.survey_id=?
    order by
        page0_.id desc

这是抛出的异常
016-2-6 22:26:24 org.hibernate.LazyInitializationException
严重: failed to lazily initialize a collection of role: zhang.model.Survey.pages, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: zhang.model.Survey.pages, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:380)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:372)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:365)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:108)
at org.hibernate.collection.PersistentBag.iterator(PersistentBag.java:272)
at MyTest.test3(MyTest.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

解决方案

List list = pageDaoImp.findEntityByHQL(hql, id);
它的实现在哪里。这里是懒惰加载的。换一句话说,它其实没有加载page对象,你在里面关闭了 session,导致你关联属性加载不了。

时间: 2024-09-08 11:24:53

问一个hibernate的懒加载的问题的相关文章

hibernate+spring mvc, 解决hibernate 对象懒加载 json序列化问题

引用地址 在使用Spring MVC时,@ResponseBody 注解的方法返回一个有懒加载对象的时候出现了异常,以登录为例:   Java代码   @RequestMapping("login")       @ResponseBody       public Object login(@RequestParam String username,@RequestParam String password){           List<User> list=user

hibernate去除懒加载后出现了问题

问题描述 有两张表,draft表和playissue表,draft单向关联playissue表.所有懒加载都已经去除.我在dao层查询draft表,把playissue加载入draft中.Stringhql="fromBetDraftbdwherebd.tranceCode=?";BetDraftbetDraft=(BetDraft)this.getObject(hql,tranceCode);Hibernate.initialize(betDraft.getPlayIssue());

hibernate 一对多映射 懒加载

   //从一的一端查询        //hibernate 默认使用懒加载       ClassRoom cr=(ClassRoom) session.get(ClassRoom.class, 1);//get方法不会懒加载,会直接查询ClassRoom数据库,       //但不会发出查询和他一对多的两个数据库的sql       cr.getStu();//默认设置,不会发出sql语句,在<class name="ClassRoom" table="t_cl

Hibernate懒加载解析

Hibernate懒加载解析 在Hibernate框架中,当我们要访问的数据量过大时,明显用缓存不太合适, 因为内存容量有限 ,为了减少并发量,减少系统资源的消耗,这时Hibernate用懒加载机制来弥补这种缺陷,但是这只是弥补而不是用了懒加载总体性能就提高了. 我们所说的懒加载也被称为延迟加载,它在查询的时候不会立刻访问数据库,而是返回代理对象,当真正去使用对象的时候才会访问数据库.    实现懒加载的前提:  1 实体类不能是final的 2 能实现懒加载的对象都是被CGLIB(反射调用)改

hibernate3-spring mvc OpenSessionInViewFilter hibernate 懒加载问题

问题描述 spring mvc OpenSessionInViewFilter hibernate 懒加载问题 之前做了一个项目是使用 springmvc 加hibernate 做的, 并且使用了 hibernate 的懒加载有用到OpenSessionInViewFilter, 现在做另一个项目, 基础代码都是上个项目的代码: 目前调试在调试权限模块, 核对了上个项目的代码基本完全一致,但是这个项目的老是无法使用懒加载,加载报 org.hibernate.LazyInitializationE

懒加载session-多数据源springmvc+hibernate 切换问题 在一次请求中多次切换不成功

问题描述 多数据源springmvc+hibernate 切换问题 在一次请求中多次切换不成功 最近写了一个多数据源的代码,结果在使用的过程中出现了在一个请求中(方法中)两个数据库交替使用的情况,最后情况是数据库切换不过来 并且在项目配置中有懒加载和OpenSessionInViewFilter 数据库一个为本地数据库一个为基金数据库 要做的事情就是在本地查询到基金代码接着再循环去基金库查询基金数据 中间报错为在本地数据库中查询不到某个表(其实是在基金库中) controller层 @Reque

hibernate懒加载能用get方法吗

问题描述 hibernate懒加载能用get方法吗 hibernate中的session.load()方法特性是使用懒加载,那么请问hibernate中的session.get()方法在什么情况下也是使用的懒加载?还是说get方法没有懒加载,都是立即加载?看教程的时候发现测试集合的懒加载是用get方法取一对多的一对象而不是load方法 解决方案 http://blog.csdn.net/yaorongwang0521/article/details/7074573 解决方案二: get和load

spring mvc-Spring mvc结合Hibernate中实现ajxa出现懒加载异常

问题描述 Spring mvc结合Hibernate中实现ajxa出现懒加载异常 我要实现一个选择省份加载城市列表,然后选择城市加载区列表的操作,但是我在加载城市的时候一直报懒加载异常,session提前关闭,我觉得是因为我城市中设置的private Province province 对象的原因,请问大神这有什么好的解决办法吗 解决方案 懒加载的话,你直接用fetch属性设为eager就行了,session提前关闭,,可能是你的openSessionInView,,这个过滤器没用,,而且省市区

hibernate get方法 懒加载异常

问题描述 hibernate用get方法怎么也懒加载异常呢?情况是这样device类中有个product类 他们的关系是多对一 ,many to one 这里没有显示的写上lazy属性(默认是proxy吧?),不过many-to-one这里确定要懒加载的而现在我想通过get方法得到device对象,在得到product,hibernate为什么会报懒加载异常呢?不是说get不会看懒加载么? 问题补充:可是多对一的一方,其他人想要延时加载啊,毕竟不是每查一个device类就一定要知道product