`
猜不透
  • 浏览: 134589 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

could not initialize proxy - no Session

阅读更多
当代码一调用findUser方法当运行session.load()方法时就会抛出如下异常
public static void main(String[] args) {
User user = new User();
user.setName("xiaozhang");
user.setTime(new Date());
User u=(User)HibernateUtil.findUser(user, 1); //代码一
System.out.println(u.getName());
}

public static Object findUser(Class clazz,Serializable id) {
Transaction tra = null;
Session session = null;
try {
session = HibernateUtil.getSession();
Object entity=session.get(clazz,id);
return entity;
} finally {
if (session != null)
session.close();
}
}
Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - no Session

hibernate中的load方法属于懒加载,当第一次真正用用到查询的时候load方法才会真正去访问数据库,所以会抛出异常
而使用session.get()方法时,会避免这种错误,而且load方法永远都不会返回空值
分享到:
评论

相关推荐

    S2S3H3整合以及泛型Dao与Service封装

    2.2.3.1+spring-framework-3.1.0+hibernate-distribution-3.6.8+JSON+MySQL+Annotation,并且对Dao和Service进行了封装,内含.jar包,并且解决了一对多双向关联的could not initialize proxy - no Session错误,同时...

    集成spring的hibernate懒加载

    当你尝试在Controller层或者视图层访问懒加载的属性时,如果Session已经关闭("no Session..."错误),就会抛出`org.hibernate.LazyInitializationException`。这是因为懒加载的代理对象需要Session来执行数据库查询...

    基于SSH框架的BBS论坛JavaEE项目源码

    7.注册如果发送邮件激活的方式出错(返回页面错误org.hibernate.LazyInitializationException: could not initialize proxy - no Session) 8.禁止用户后不允许登录、发帖、回帖等 9.后台会员搜索中文名搜索乱码 ...

    JAVA错误文档[归纳].pdf

    7. **Action的返回方法出错,could not initialize proxy - no Session** 这可能是在Hibernate操作中没有正确初始化Session。确保在访问数据库之前已打开Session,并在完成后关闭。 8. **查询数据出现乱码问题** ...

    Hibernate配置常见错误

    错误表现:在Session关闭后尝试访问懒加载属性,抛出“org.hibernate.LazyInitializationException: could not initialize proxy - no Session”异常。 解决方案:理解并合理使用Open Session in View(OSIV)模式...

    java开源论坛jeebbs系统源码包

    7.注册如果发送邮件激活的方式出错(返回页面错误org.hibernate.LazyInitializationException: could not initialize proxy - no Session) 8.禁止用户后不允许登录、发帖、回帖等 9.后台会员搜索中文名搜索乱码 ...

    Hibernate映射导致的几个异常

    Could not initialize proxy - the owning Session was closed 这是Hibernate懒加载机制中的常见异常,当尝试访问一个已被关闭的Session中的懒加载属性时触发。例如,如果Session在使用`setFetchMode(FetchMode....

    Hibernate延迟加载以及利用Spring

    Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed ``` - **日志记录**:为了更好地诊断问题,可以使用log4j等工具进行日志...

    php.ini-development

    There is no name validation. If PHP can't find an expected ; directive because it is not set or is mistyped, a default value will be used. ; The value can be a string, a number, a PHP constant (e.g....

Global site tag (gtag.js) - Google Analytics