无法使FetchType.EAGER与@ElementCollection一起使用

时间:2018-11-28 13:29:21

标签: hibernate spring-data-jpa lazy-loading eager-loading transactional

我在变量上有以下注释:

@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "question_translation",
                 foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_question_translation_question"),
                 joinColumns = @JoinColumn(name = "question_id"))
@MapKeyColumn(name = "language", nullable = false)
@MapKeyEnumerated(EnumType.STRING)
@Column(name = "translation", nullable = false)
private Map<Language, String> translations;

当我在translations.get(Language.EN)之外进行@Transactional时,我得到: org.hibernate.LazyInitializationException: could not initialize proxy - no Session

版本:

spring boot: <version>2.0.3.RELEASE</version>
<hibernate.version>5.2.17.Final</hibernate.version>
<hibernate-jpa-2.1-api.version>1.0.2.Final</hibernate-jpa-2.1-api.version>

我想念什么?

编辑:

进一步搜索之后,我认为问题是因为我使用了spring-data及其存储库...他们似乎忽略了提取类型...

1 个答案:

答案 0 :(得分:0)

我知道出了什么问题:spring-data会忽略获取类型,直到您在存储库中的方法和实体上都指定了@EntityGraph批注为止。

需要解决的部分是,您无法覆盖JpaRepository中的方法并向其中添加@EntityGraph,因为它会被忽略。

您需要在存储库中编写自己的方法...例如:

@EntityGraph(value = "graphNameDefinedOnEntity", type = EntityGraph.EntityGraphType.LOAD)
QuestionEntity getById(Long id);

这与getOne(Long id)提供的JpaRepository有很大冲突。极度混乱。因此,最好将其命名为getByIdEagerlyLoaded并用@Query注释自己编写查询

相关问题