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方法永远都不会返回空值

你可能感兴趣的:(Hibernate,session,get,load)