延迟加载不适用于休眠中的@Formula



我正在尝试使我的一个字段可计算,但我真的不想在检索实体时一直计算它。我想要的是,仅在当前查询需要或只是调用 getter 时才计算它。这就是我使用@Formula的原因:

@Basic(fetch = FetchType.LAZY)
@Formula("(SELECT max(myEntity.CREATION_TIME) FROM MyEntity myEntity 
WHERE myEntity.account_id = id)")
private LocalDateTime entitiesModifiedDate;

为了使它工作,我使用这样的字节码工具:

<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.3</version>
<executions>
<execution>
<id>Instrument domain classes</id>
<configuration>
<tasks>
<taskdef name="instrument" classname="org.hibernate.tool.instrument.javassist.InstrumentTask">
<classpath>
<path refid="maven.dependency.classpath" />
<path refid="maven.plugin.classpath" />
</classpath>
</taskdef>
<instrument verbose="true">
<fileset dir="${project.build.outputDirectory}">
<include name="**/entity/*.class" />
</fileset>
</instrument>
</tasks>
</configuration>
<phase>process-classes</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>

我在这里面临两个问题:

  1. 即使我从另一个问题中得到这个,语法似乎不正确。我有的错误:

发生了 Ant BuildException:仪器不支持"verbose"属性:类型不支持"verbose"属性。

  1. 如果我删除 verbose="true",它可以工作,但是,子查询是我的实体的每个查询的一部分(无效(。

还有什么应该做的吗?

这里我举了一个例子:http://tricksdev.blogspot.ru/2009/03/hibernate-bytecode-instrumentation.html

更新:

查询示例:

SELECT
...{fields}...,
(
SELECT
MAX(event.creation_time)
FROM
MyEntity myEntity
WHERE
myEntity.accountId = account1_.id
) AS formula0_
FROM
Table1 table10_
CROSS JOIN account_table account1_
WHERE
table10_.account_id = account1_.id
AND
account1_.user_id = 1

使用hibernate-enhance-maven-plugin,或尝试使用maven-antrun-plugin最新版本(1.8(

<plugins>
<plugin>
<groupId>org.hibernate.orm.tooling</groupId>
<artifactId>hibernate-enhance-maven-plugin</artifactId>
<executions>
<execution>
<phase>process-classes</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>

参考: https://docs.jboss.org/hibernate/orm/5.0/topical/html/bytecode/BytecodeEnhancement.html

最新更新