我正在尝试使用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; // ... }
但是,在尝试加载测试实体时,出现错误“找不到列“ TEST0_.RESULTDATE””。我还尝试了其他一些涉及@JoinFormula批注的事情,但是没有成功。我也遇到了这个答案,这似乎表明我在做的事情应该起作用,但事实并非如此。我该如何工作?
因此,我找到了解决此特定问题的方法。该latestResult属性的注释如下:
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;