java - 如何在hibernate连接映射上指定固定参数?

标签 java hibernate mapping

我有以下情况,其中有两个类/表:

public class Parent {
    @Id
    @Column(name="parent_id")
    private Integer parentId;

    @ManyToOne
    @JoinColumn(name="child_id") //Notice here that i only specified one of the two id columns of the Child class
    private Child child;
    ...
}

public class Child {
    @Id
    @Column(name="child_id")
    private Integer childId;

    @Id
    @Column(name="alive")
    private Boolean alive;

    @Column(name="name")
    private String name;
}

如您所见,child 有两个主键,这意味着我可以在两行中拥有相同的 child_id,其中一行带有 alive=true 和另一个 alive=false,但我的父级没有 alive 属性:

PARENT TABLE
parent_id | child_id
--------------------
500       | 1

CHILD TABLE
child_id | alive | name
--------------------------
1        | TRUE  | DONALD
1        | FALSE | HILLARY

我希望 hibernate 生成插入 alive 属性的 join 子句,仅当 alive=true 时,例如:

select * from Parent inner join Child on Child.child_id=Parent.child_id and Child.alive=true

有没有办法做到这一点,所以当我执行像 select p from Parent p 这样的查询时,它会按预期执行查询?

最佳答案

对于父类,您可以使用

@JoinColumnOrFormula(formula=@JoinFormula(value="(SELECT a.id 
                                                  FROM Child c 
                                                  WHERE c.child_id=child_id 
                                                  and alive=true)", 
   referencedColumnName="child_id") 

发布正确的评论作为答案

关于java - 如何在hibernate连接映射上指定固定参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40720079/

相关文章:

mapping - Automapper - 嵌套实体

sorting - grails:在域类中测试 'sort' 映射

java TimerTask增加时间?

java - 使用 @EnableWebSecurity 时,至少有一个非空 i..... 作为 @Bean。提示尝试扩展 WebSecurityConfigurerAdapter

java - 如何在 JPA 中查询 List<String> 类型的属性

java - Bean创建异常: Error creating bean with name 'userController' : Injection of autowired dependencies failed

xslt - 在 BizTalk 中映射递归结构

java - 在 Gradle 项目 IntelliJ 中激活断言

java - HttpResponse 抛出运行时错误 httpResponse = httpClient.execute(httpPost);

mysql左外连接