gpt4 book ai didi

java - 带有 map 集合的 LazyInitializationException

转载 作者:太空宇宙 更新时间:2023-11-04 07:40:42 24 4
gpt4 key购买 nike

我知道这是一个老生常谈的问题,但我找不到解决方案。我有两个 bean,其中一个有 HashMap 集合。我在尝试阅读此集合时遇到异常。已指定映射配置来立即加载此集合。

我的环境是:

  • hibernate 4.2.0
  • mysql-connector-java 5.1.24

我还有两颗 bean :

public class FeaturedDoc {
private Long id;
private Map<Feature, Float> features;

public FeaturedDoc() {
features = new HashMap<Feature, Float>();
}
(getters and setters)
}

public class Feature {
private Long id;
private String name;
private Long internalId;
(getters and setters)
}

这个bean有映射:

<class name="Feature" table="FEATURE">
<id name="id" type="long" column="ID">
<generator class="increment"/>
</id>
<property name="name" length="255" type="string" unique="true" column="NAME" index="INDEX_NAME"/>
<property name="internalId" type="long" unique="true" not-null="false" column="INTERNAL_ID" index="INDEX_INTID"/>
<sql-insert>insert into FEATURE (NAME, INTERNAL_ID, ID) values (?, ?, ?) on duplicate key update ID = ID</sql-insert>
</class>

<class name="FeaturedDoc" table="FEATURED_DOC">
<id name="id" type="long" column="ID">
<generator class="increment"/>
</id>
<map name="features" table="DOC_FEATURE" cascade="all" lazy="false" fetch="join">
<key column="ID"></key>
<map-key-many-to-many column="FEATURE_ID" class="Feature"/>
<element column="value" type="float"/>
</map>
</class>

我还有 DAO 层,其方法为:

public FeaturedDoc read(long id) {
FeaturedDoc fd = null;
try {
session.beginTransaction();
fd = session.get(FeaturedDoc.class, id);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
} finally {
close();
}
return fd;
}

当我尝试做这样的事情时:

FeaturedDoc fd = daoService.read(26);
System.out.println(fd.getFeatures());

我遇到异常

org.hibernate.LazyInitializationException: could not initialize proxy - no Session

你知道我应该如何修复这个错误吗?

最佳答案

假设其他一切都正常(在映射中),您是否尝试过将 lazy="false" 放在 cascade="all" 之前。我发现这是我的映射中的一个问题,导致了此 LazyInitializationException 错误。

此顺序显示在以下 Hibernate 引用中:http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/collections.html

关于java - 带有 map 集合的 LazyInitializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16102801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com