Search code examples
hibernatejpajoinjoincolumn

Conditional/composite JoinColumn In JPA/Hibernate


In one of my classes, say Location, I have something like this:

private List<Magician> magicians;

...

@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name="location_id")
public List<Magician> getMagicians() {
    return magicians;
} 

public void setMagicians(List<Magician> magicians) {
    this.magicians = magicians;
}

where Magician has variables

private Integer id;
private Integer location_id;
private Boolean active;

Now I would like to modify the getter annotation so as to get only the magicians for which active is true.

How can I achieve this?

Thanks for your attention.


Solution

  • In Hibernate my issue can be solved using a filter, as explained here : https://stackoverflow.com/a/6920847/1966869. The xml version, which I have just tested and appears quite practical, is described here : http://www.mkyong.com/hibernate/hibernate-data-filter-example-xml-and-annotation/. There might be other solutions using @Where (How to use @Where in Hibernate) or @JoinFormula (@JoinFormula and @OneToMany definition - poor documentation), but I have not tested them.