我有以下情况,其中有两个类/表:
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/