当代码一调用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方法永远都不会返回空值
分享到:
相关推荐
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错误,同时...
当你尝试在Controller层或者视图层访问懒加载的属性时,如果Session已经关闭("no Session..."错误),就会抛出`org.hibernate.LazyInitializationException`。这是因为懒加载的代理对象需要Session来执行数据库查询...
7.注册如果发送邮件激活的方式出错(返回页面错误org.hibernate.LazyInitializationException: could not initialize proxy - no Session) 8.禁止用户后不允许登录、发帖、回帖等 9.后台会员搜索中文名搜索乱码 ...
7. **Action的返回方法出错,could not initialize proxy - no Session** 这可能是在Hibernate操作中没有正确初始化Session。确保在访问数据库之前已打开Session,并在完成后关闭。 8. **查询数据出现乱码问题** ...
错误表现:在Session关闭后尝试访问懒加载属性,抛出“org.hibernate.LazyInitializationException: could not initialize proxy - no Session”异常。 解决方案:理解并合理使用Open Session in View(OSIV)模式...
7.注册如果发送邮件激活的方式出错(返回页面错误org.hibernate.LazyInitializationException: could not initialize proxy - no Session) 8.禁止用户后不允许登录、发帖、回帖等 9.后台会员搜索中文名搜索乱码 ...
Could not initialize proxy - the owning Session was closed 这是Hibernate懒加载机制中的常见异常,当尝试访问一个已被关闭的Session中的懒加载属性时触发。例如,如果Session在使用`setFetchMode(FetchMode....
Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed ``` - **日志记录**:为了更好地诊断问题,可以使用log4j等工具进行日志...
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....