2015-02-23 70 views
3

我试图从另一个表中使用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; 
    } 

    // ... 
} 

结果类看起来是这样的:

@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注释的事情,但没有取得任何成功。我也遇到了this answer,这似乎表明我正在做的事情应该工作,但事实并非如此。我如何完成这项工作?

回答

6

所以,我找到了解决这个问题的方案。 latestResult财产注释如下:

@ManyToOne 
@JoinColumnsOrFormulas({ 
    @JoinColumnOrFormula([email protected](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; 
相关问题