2015-02-23 67 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; 
相關問題