hibernate_6、(懒加载)

tangkenyi 贡献于2013-12-12

作者 张润华  创建于2008-09-11 17:20:00   修改者user  修改于2013-11-11 01:44:00字数2272

文档摘要:LazyLoad懒加载
关键词:

LazyLoad 懒加载 实体类 public class UserInfo { private int id ; private String username ; private Date birthday ; private String sex ; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } } 配置文件 测试类 public class LazyLoadTest { public static void main(String[] args) { add() ; UserInfo user = getUser(1); System.out.println(user.getUsername()); } static UserInfo getUser(int id ){ UserInfo userinfo = null ; Session session = null ; Transaction tx = null ; try { session = HibernateSessionFactory.getSession(); tx = session.beginTransaction() ; userinfo = (UserInfo) session.load(UserInfo.class, id); tx.commit() ; } finally{ if(session != null ){ session.close(); } } return userinfo ; } static void add(){ Session session = null ; Transaction tx = null ; try { session = HibernateSessionFactory.getSession(); tx = session.beginTransaction(); UserInfo userinfo = new UserInfo(); userinfo.setBirthday(new Date()); userinfo.setUsername("username"); userinfo.setSex("男"); session.save(userinfo); tx.commit(); }finally{ if(session != null ){ session.close(); } } } } 产生如下的错误 Hibernate: select hibernate_sequence.nextval from dual Hibernate: insert into UserInfo (username, birthday, sex, id) values (?, ?, ?, ?)并没有产生查询语句 Load 方法使用时只有真正的开始使用该对象的时候才会到数据库中进行查询 Exception in thread "main" org.hibernate.LazyInitializationException: 此异常 是由没有对对象进行初始化而造成的错误 could not initialize proxy - no Session at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:132 ) at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:174) at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190) at com.tang.beans.UserInfo_$$_javassist_2.getUsername(UserInfo_$$_javassist_2.java) at com.tang.test.LazyLoadTest.main(LazyLoadTest.java:17)

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 3 金币 [ 分享文档获得金币 ] 1 人已下载

下载文档