我正在尝试使用Hibernate的@Formula注释从另一个表中检索实体。给出以下代码:
@Entity
class Test {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id = null;
// ...
@Formula("(SELECT r FROM Result r WHERE test_id = id AND resultDate = (SELECT MAX(resultDate) FROM Result WHERE test_id = id))")
private Result lastestResult;
// ...
public Result getLatestResult() {
return latestResult;
}
// ...
}
Result类如下所示:
@Entity
class Result {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id = null;
@ManyToOne
private Test test;
// ...
}
但是在尝试加载Test实体时,我收到错误“Column”TEST0_.RESULTDATE“not found”。我已经尝试过其他一些涉及@JoinFormula注释的东西,但没有任何成功。我也遇到了this answer,这似乎表明我正在做的事情应该有效,但事实并非如此。我如何使这项工作?
答案 0 :(得分:8)
所以,我找到了解决这个特殊问题的方法。 latestResult
属性的注释如下:
@ManyToOne
@JoinColumnsOrFormulas({
@JoinColumnOrFormula(formula=@JoinFormula(value="(SELECT r.id FROM Result r WHERE resultDate = (SELECT MAX(sqr.resultDate) FROM Result sqr WHERE sqr.test_id = id))", referencedColumnName="id")),
})
private Result latestResult;