could not initialize proxy - no Session
程序员文章站
2022-07-13 16:19:30
...
当代码一调用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方法永远都不会返回空值
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方法永远都不会返回空值
推荐阅读
-
Plsql Developer连接Oracle时出现Could not initialize oci.dll解决方案
-
【J2SE】java.lang.NoClassDefFoundError: Could not initialize class xxx 原因
-
jspgou商城部署时报错:Could not open Hibernate Session for transaction; nested exception is org.hibernate.ex
-
java.lang.NoClassDefoundError:Could not initialize class sun.awt.X11GraphicsEnvironment异常
-
Java:提示Could not initialize class sun.awt.X11GraphicsEnvironment
-
java导出excel:Could not initialize class sun.awt.X11GraphicsEnvironment
-
Caused by: java.lang.NoClassDefFoundError: Could not initialize class sun.awt.X11GraphicsEnvironment
-
could not initialize proxy - no Session
-
解决:org.hibernate.LazyInitializationException: could not initialize proxy - no Session
-
Fatal error: session_start(): Failed to initialize storage module: files问题解决方法