annotation to filter results of a @OneToMany association

Viewed 43705

I have parent/child relationship between two tables, and the corresponding mapping in my Java classes. The tables roughly look like that:

A (ref number, stuff varchar2(4000))
B (a_ref number, other number, foo varchar2(200))

and the Java code:

@Entity
class A {
    @Id
    @Column(name = "REF")
    private int ref;

    @OneToMany
    @JoinColumn(name = "A_REF", referencedName = "REF")
    private Set<B> bs;
}

@Entity
class B {
    @Id
    @Column(name = "A_REF")
    private int aRef;

    @Id
    @Column(name = "OTHER")
    private int other;
}

This works fine, but I'd like to add a filter on the rows that I retrieve from the child table. The query that is generated looks like:

select a_ref, other, foo from B where a_ref = ?

And I'd like it to be:

select a_ref, other, foo from B where a_ref = ? and other = 123

The additional filter would be only a column name and a hard-coded value. Is there a way to do that using hibernate annotations?

I've looked at @JoinFormula, but with that I always have to reference a column name from the parent table (in the name attribute of the JoinFormula).

Thanks in advance for any advice.

4 Answers

If I am understanding the question right, there is a way to do this with javax.persistence annotations (I used this on a ManyToOne myself, and tailored the answer from here):

@JoinColumns({
    @JoinColumn(name = "A_REF", referencedColumnName = "REF"),
    @JoinColumn(name = "B_TABLE_NAME.OTHER", referencedColumnName = "'123'")})
@OneToMany
private Set<B> bs;

Note the single quotes in the referencedColumnName, this is the value you are looking for.

More information here.

Related