我试图使用延迟加载方法从数据库加载数据,但发生异常,我使用的是Karaf 3.0.0,Hibernate 4.2.2.Final和JPA 2。 我还尝试在发出请求之前打开一个事务,但问题仍然存在:
EntityManager em = HibernateUtil.getEntityManager();
em.getTransaction().begin();
List<Position> list = taxiEntity.getPositionsList();
em.getTransaction().commit();
em.close();
例外是:
Exception in thread "AWT-EventQueue-0" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: fr.pu.e
ntities.Toolbar.mainWindowList, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwL
azyInitializationException(AbstractPersistentCollection.java:566)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTe
mporarySessionIfNeeded(AbstractPersistentCollection.java:186)
at org.hibernate.collection.internal.AbstractPersistentCollection.initia
lize(AbstractPersistentCollection.java:545)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(A
bstractPersistentCollection.java:124)
at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBa
g.java:266)
at fr.actiasodielec.dsw802.toolbar.instantiator.MainToolbar.<init>(MainT
oolbar.java:54)
at fr.actiasodielec.dsw802.mainwindow.MainWindowGui.initGUI(MainWindowGu
i.java:78)
at fr.actiasodielec.dsw802.mainwindow.InitializationSW.process(Initializ
ationSW.java:112)
答案 0 :(得分:1)
这是因为您在事务(会话)之外获取延迟集合。 你有两种方式:
设置hibernate属性(对于SessionFactory):
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>