0

我正在尝试使用延迟加载方法从数据库加载数据,但发生异常,我使用的是 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)
4

1 回答 1

1

这是因为您在事务(会话)之外获取惰性集合。你有两种方法:

  1. 急切地获取所需的集合(链接
  2. 设置休眠属性(对于 SessionFactory):

    <prop key="hibernate.enable_lazy_load_no_trans">true</prop>
    
于 2014-04-21T11:06:30.660 回答