问题描述
在通过Hibernate查询Bean信息时报以下异常信息:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session |
分析:这错误很常见,字面意义就是不能被初始化,因为session已经关闭了。简单理解就是因为,你使用了lazy=true,这样hibernate在从数据库中调数据的时候是不会把关联的对象查出来的,而是保存一个获取值得方法,在你使用getXXX()调用的时候,hiberante会利用这个保存的方法去从数据库中取数据。而往往我们在jsp页面中使用getXXX()准备展示数据的时候,session早已经在dao中就关闭了,如果是实体Bean是通过注解模式被注入的(配置模式不再此文讨论范围内),则解决方法如下:
测试类:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"file:WebContent/WEB-INF/applicationContext2.xml"}) public class otherTest{ @Autowired private HibernateTemplate hibernateTemplate;
// 必须设置set方法 public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } //通过id查询指定用户 //注意:需在User设置@org.hibernate.annotations.Proxy(lazy = false) @Test public void findUserById(){ User u= hibernateTemplate.load(User.class, 31); System.out.println(u);//User [id=31, username=王大大3, password=111, email=wql025@sina.com] } }
实体Bean
@Entity @Table(name="t_user") @org.hibernate.annotations.Proxy(lazy = false)//设置立即加载 public class User { private int id; private String username; private String password; private String email; @GeneratedValue @Id public int getId() { return id; } public void setId(int id) { this.id = id; } @NotEmpty(message="用户名不能为空") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Size(min=1,max=10,message="密码的长度应该在1和10之间") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Email(message="邮箱格式不正确") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public User(String username, String password, String email) { super(); this.username = username; this.password = password; this.email = email; } public User(){} @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + "]"; } }
附:如果是配置模式,解决方法参考下文:
http://blog.csdn.net/s_good/article/details/7411642
鸣谢:http://bbs.csdn.net/topics/390522138
原文:http://www.cnblogs.com/wql025/p/4817463.html