Reputation: 7709
I have the following case, where I have two classes/tables:
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;
}
As you can see, child
has two primary keys, which means i can have the same child_id
in two rows, one with alive=true
and another with alive=false
, but i don't have the alive
attribute on the parent:
PARENT TABLE
parent_id | child_id
--------------------
500 | 1
CHILD TABLE
child_id | alive | name
--------------------------
1 | TRUE | DONALD
1 | FALSE | HILLARY
I want hibernate to generate the join clause inserting the alive
attribute, only when alive=true
, for example:
select * from Parent inner join Child on Child.child_id=Parent.child_id and Child.alive=true
Is there a way to do this, so when i execute a query like select p from Parent p
it executes the query as expected?
Upvotes: 0
Views: 990
Reputation: 57421
For the Parent class you can use
@JoinColumnOrFormula(formula=@JoinFormula(value="(SELECT a.id
FROM Child c
WHERE c.child_id=child_id
and alive=true)",
referencedColumnName="child_id")
Posted correct comment as an answer
Upvotes: 1