Hibernate抛出了org.hibernate.LazyInitializationException

时间:2016-02-01 13:03:41

标签: java hibernate postgresql hibernate-mapping

尝试使用hibernate从数据库中使用Purchase Object填充javaFX表视图。为了澄清一点,我有与多对多关系的购买和产品实体,我已经应用了这个方法[我自己的代码](Hibernate many to many relationship with extras columns)来映射这种关系。 我收到这个错误:

Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: model.Purchase.lineItems, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:567)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:205)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:546)
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:133)
    at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:163)
    at java.util.AbstractCollection.addAll(AbstractCollection.java:343)
    at javafx.collections.ModifiableObservableListBase.addAll(ModifiableObservableListBase.java:99)
    at controller.purchase.PurchaseController.setPurchaseHeader(PurchaseController.java:254)
    at controller.purchase.PurchaseController.btnEditClicked(PurchaseController.java:244)

这是我从数据库中获取所有内容的代码: 请注意,我使用thoes元素填充tableView,并为每个具有LineItems的Purchase填充。

 public ObservableList<Purchase> findAll() {
        try {
            if (!session.isOpen())
                session = DatabaseUtil.getSessionFactory().openSession();
            session.beginTransaction();
            Criteria c = session.createCriteria(Purchase.class);
            c.setFetchMode("lineItems", FetchMode.JOIN);
            Query query = session.createQuery("  from Purchase ");
            ObservableList<Purchase> list = FXCollections.observableArrayList(query.list());
            session.getTransaction().commit();
            session.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

1 个答案:

答案 0 :(得分:0)

这是因为您尝试在Session上下文之外访问这些lineItems集合,并且这些lineItems对象不是您用于获取Purchase的实际查询所带来的

在您执行选择购买项目的休眠代码中,您应该为这些lineItems添加获取连接模式

喜欢:

@Bean(name="multipartResolver")
public CommonsMultipartResolver multipartResolver(){
    return new CommonsMultipartResolver();
}

修改

阅读完代码后,我建议如下:

Criteria c = sessionFactory.getCurrentSession().createCriteria(Purchase.class);
c.setFetchMode("lineItems", FetchMode.JOIN);

然后将List包装到此调用调用之外的另一个ObservableList中