问题描述
@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:无法执行请求的延迟初始化[Version.mappings]-没有会话,并且设置不允许在会话外部加载
解决方法
我建议将表拆分为两个单独的实体,并定义一个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来展示我的建议在行动中。该仓库是一个具有3个独立端点的Spring Boot应用程序:
-
/books-without-author/{id}
==>获取没有作者的书 -
/books-with-author-exception/{id}
==>尝试与作者联系,但由于交易无法加载代理而抛出异常 -
/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_.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使用获取所有属性立即在第一个查询中获取延迟属性。