Action:
public Cardinfo findById(Long id) { Session session = HibernateSessionFactory.getSession(); Transaction tx = null; Cardinfo cinfo = null; try { tx = session.beginTransaction(); cinfo = (Cardinfo) session.load(Cardinfo.class, id); tx.commit(); } catch (RuntimeException re) { tx.rollback(); log.error("==CardinfoServices findById failed==", re); } finally { session.close(); } return cinfo; }
String cidLoad = request.getParameter("cidLoad"); Cardinfo cardinfo = cardinfoSer.findById(new Long(cidLoad)); cardinfoForm.setCardid(new Long(cidLoad)); cardinfoForm.setCardname(cardinfo.getCardname()); cardinfoForm.setPhonenum(cardinfo.getPhonenum()); cardinfoForm.setCardstate(cardinfo.getCardstate()); cardinfoForm.setOtherinfo(cardinfo.getOtherinfo()); System.out.println("oid: " + cardinfo.getCardownerinfo().getOwnerid()); System.out.println("oid: " + cardinfo.getCardownerinfo().getOwnername());
错误指向这行:
cardinfoForm.setCardname(cardinfo.getCardname());
于是修改:
public Cardinfo findById(Long id) { Session session = HibernateSessionFactory.getSession(); Transaction tx = null; Cardinfo cinfo = null; try { tx = session.beginTransaction(); cinfo = (Cardinfo) session.load(Cardinfo.class, id); Hibernate.initialize(cinfo); tx.commit(); } catch (RuntimeException re) { tx.rollback(); log.error("==CardinfoServices findById failed==", re); } finally { session.close(); } return cinfo; }
程序还是报错:org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed
错误指向:
System.out.println("oid: "
+ cardinfo.getCardownerinfo().getOwnername());
这该如何解决呢?
------解决方法--------------------------------------------------------
查看下关于hibernate检索策略的文章
不知道你是怎么关联的
只设置关联级别的lazy=false不一定起作用 还要看对方类级别的lazy
------解决方法--------------------------------------------------------
cardinfoForm.setCardname(cardinfo.getCardname());还是
cardinfo.getCardownerinfo().getOwnername());
两帖说的好像不统一啊
如果是第二句,就是关联的对象没有查到,为什么呢/
你cinfo = (Cardinfo) session.load(Cardinfo.class, id);
Hibernate.initialize(cinfo);根本没有作用,因为load加载了Cardinfo但它没有加载Cardownerinfo所以不可能得到ownername(many-to-one 如果lazy没有设置或是设为true)
你应该是Hibernate.initialize(cinfo.getOwnerinfo());
如果是第一句,不至于这样吧.查询它本身也会出错?LOAD先加载ID,如果只要ID的话,就不会再加载其它的.但如果有需要其它属性,应该也会查出的啊
------解决方法--------------------------------------------------------
finally {
session.close();
}
你都把session关闭了,怎么会延迟加载呢?
------解决方法--------------------------------------------------------