QueryDsl 获取延迟 属性

QueryDsl fetch lazy property

我有一个 属性 通常是延迟获取的:

@Entity
class Version(...,
              @Basic(fetch = FetchType.LAZY)
              @Type(type = "text")
              var mappings: String? = null) {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private val id = 0
}

但有时我需要急切地获取它。我如何使用 QueryDsl 执行此操作? 这是我目前拥有的:

JPAQuery<Any>(entityManager).from(QVersion.version)
        .where(...)
        .select(QVersion.version)
        .fetchOne()

但是当我稍后尝试访问 属性 时,这会导致异常:

org.hibernate.LazyInitializationException: Unable to perform requested lazy initialization [Version.mappings] - no session and settings disallow loading outside the Session

我建议将 table 拆分为两个单独的实体并定义一个 lazy OneToOne 关系,以便您可以在需要时通过 QueryDSL 急切地获取它。因此,对于您的示例,您可能有以下实体:

@Entity
@Table(name="version")
class Version{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private val id = 0;
    @OneToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "id", referencedColumnName = "id")
    private VersionMappings mappings;
}

@Entity
@Table(name="version")
VersionMappings{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private val id = 0;
    @Basic(fetch = FetchType.LAZY)
    @Type(type = "text")
    var mappings: String? = null);
}

如果语法有误,请见谅;因为我不熟悉Kotlin。然后就可以按如下方式进行预取:

    QVersion version = QVersion.version;

    Version versionWithEagerlyFetchedMapping = JPAQuery<>(entityManager).from(version).where(version.id.eq(id)).rightJoin(version.versionMapping).fetchJoin().select(version).fetchOne();

我准备按照 github repo 来展示我的建议。回购协议是一个 Spring 具有 3 个独立端点的引导应用程序:

  1. /books-without-author/{id} ==> 获取没有作者的书
  2. /books-with-author-exception/{id} ==> 尝试获取作者的书,但由于事务无法加载代理而抛出异常
  3. /books-with-author/{id} ==> 按照我上面的建议,通过 QueryDSL 急切获取作者的书。

您可以检查控制台日志以查看预取的工作。当您调用上面的第三个端点时,您将看到生成以下查询: select book0_.id as id1_0_0_, bookauthor1_.id as id1_0_1_, book0_.name as name2_0_0_, book0_.publish_year as publish_3_0_0_, book0_.version as version4_0_0_, bookauthor1_.author as author5_0_1_ from book book0_ right outer join book bookauthor1_ on book0_.id=bookauthor1_.id where book0_.id=?

另一方面,第一个端点将生成类似 select book0_.id as id1_0_0_, book0_.name as name2_0_0_, book0_.publish_year as publish_3_0_0_, book0_.version as version4_0_0_ from book book0_ where book0_.id=?

的查询

对此有一个非常简单的解决方案:.fetchAll()

JPAQuery<Any>(entityManager).from(QVersion.version)
        .fetchAll()  // <- here
        .where(...)
        .select(QVersion.version)
        .fetchOne()

相关hibernate documentation:

If you are using property-level lazy fetching (with bytecode instrumentation), it is possible to force Hibernate to fetch the lazy properties in the first query immediately using fetch all properties.