Issue
I need to fill a Entity with the children entities and it works well when I need all children but now I only want to have a few ones.
For example, I have Owner 1-----n Pet
If I ownerRepositoty.findAll()
; I get all owners with each one having an array of all he's pets. But let's say I want to get all the owners with the pet array having only the ones which name starts with N.
Example of the parent entity:
public class Owner {
@OneToMany(mappedBy="Owner")
private Set<Pet> pets; //This gets filled with all pets
//getters & setters
}
And the child entity:
public class Pet {
@ManyToOne
@JoinColumn(name="owner_id", nullable=false)
private Owner owner;
//getters & setters
}
I tried with a JOIN FETCH
as explained here in the repository query but It just made a normal sql JOIN
which is not what I'm looking for.
Any ideas?
Solution
I found the way to do this:
You can use the @Where annotation to filter the childs of a one to many
or a many to many
relationship.
public class Owner {
@OneToMany(mappedBy="Owner")
@Where(clause = "name like 'N%'")
private Set<Pet> pets; //This gets filled with pets with a name starting with N
//getters & setters
}
Answered By - Carlos López Marí
Answer Checked By - Candace Johnson (JavaFixing Volunteer)