I have a Person table and a join table, containing people's relations. I have it set up to get people and their children, but I only want to get 'good' persons and filter out the 'evil' ones. To that end I have added a @Where annotation to my entity, like so:
The Person entity:
Code:
@Entity
@Table(name = "person")
@Where(clause = "personality <> 'EVIL'")
public class Person {
@Id
private int id;
private String name;
private String personality;
@OneToMany
@JoinTable(name = "relations",
joinColumns = { @JoinColumn(name = "pid") },
inverseJoinColumns = { @JoinColumn(name = "cid") }
)
private List<Person> children;
// Getters & setters...
}
The test data:
Code:
--Evil parent, good child
INSERT INTO person (id, name, personality) VALUES (1, 'Darth Vader', 'EVIL');
INSERT INTO person (id, name, personality) VALUES (2, 'Luke Skywalker', 'GOOD');
INSERT INTO relations (pid, cid) VALUES (1, 2);
--Good parent, evil child
INSERT INTO person (id, name, personality) VALUES (3, 'Rosemary', 'GOOD');
INSERT INTO person (id, name, personality) VALUES (4, 'Rosemary\'s Baby', 'EVIL');
INSERT INTO relations (pid, cid) VALUES (3, 4);
Test code:
Code:
// Get evil parent - should be filtered out.
Person darthVader = personRepository.getPerson(1);
assertNull(darthVader);
// Get good parent - should be found.
Person rosemary = personRepository.getPerson(3);
assertNotNull(rosemary);
// Get children - should be filtered out.
List<Person> babies = rosemary.getChildren();
assertEquals(0, babies.size()); // <-- Assertion error! Finds Rosemay's baby!
In the log I can see that the extra where clause is present when fetching the parent...
Code:
select
parent0_.id as id0_0_,
parent0_.name as name0_0_,
parent0_.personality as personality0_0_
from
person person0_
where
person0_.id=?
and (
person0_.personality <> 'EVIL'
)
...whereas it is not, when fetching the children.
Code:
select
children0_.pid as pid0_1_,
children0_.cid as cid1_,
person1_.id as id0_0_,
person1_.name as name0_0_,
person1_.personality as personality0_0_
from
relations children0_
inner join
person person1_
on children0_.cid=person1_.id
where
children0_.pid=?
How can I filter out the evil children as well?
Thanks!