使用Hibernate公式从另一个表中选择一个实体 [英] Selecting an entity from another table using a Hibernate formula

查看:126
本文介绍了使用Hibernate公式从另一个表中选择一个实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Hibernate的@Formula注解从另一个表中检索一个实体。给出以下代码:

I'm attempting to retrieve an entity from another table using Hibernate's @Formula annotation. Given the following code:

@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;
    }

    // ...
}



<

The Result class looks like this:

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

But upon attempting to load a Test entity, I'm getting the error 'Column "TEST0_.RESULTDATE" not found'. I've tried a few other things as well involving the @JoinFormula annotation, but without any success. I also came across this answer, which seems to indicate that what I'm doing should work, but it doesn't. How do I make this work?

推荐答案

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

So, I've found the solution to this particular problem. Annotations on the latestResult property are as follows:

@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;

这篇关于使用Hibernate公式从另一个表中选择一个实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆