I have two classes: Topic and Narrative. A topic has one-to-many narratives. I want to impose a filter such that only narratives with a particular state value are returned when I look up a topic.
@Entity
public class Topic
{
private Long id = 0L;
private Set<Narrative> narratives = new HashSet<Narrative>();
@Id
@GeneratedValue
public Long getId()...
public void setId(Long id)...
@OneToMany(mappedBy="topic")
@Filter(name="byState", condition=":state = state")
public Set<Narrative> getNarratives()
{
return narratives;
}
public void setNarratives(Set<Narrative> narratives)
{
this.narratives = narratives;
}
}
@Entity
@FilterDef(name="byState", defaultCondition=":state = state",
parameters=@ParamDef(name="state",type="string"))
@Filter(name="byState", condition=":state = state")
public class Narrative
{
private Long id = 0L;
private String content = "";
private String state = "";
private Topic topic = null;
@Id
@GeneratedValue
public Long getId()....
public void setId(Long id)...
public Topic getTopic()...
public void setTopic()...
public String getState()...
public void setState(String state)....
public String getContent()....
public void setContent()....
}
@Test
public void FindSystemById(){
//for this test, the indicated topic has two narratives,
//one is "published" and the other is "draft"
session.enableFilter("byState").setParameter("state", "published");
Topic result = null;
result = TopicDao.findById(new Long(1), noLock); //
assertNotNull(result); //this always passes
System.out.println(result.getNarratives().size(); //this always returns 2
assertTrue(result.getNarratives().size() == 1); //this always fails
}
The sql code does not show the filter being applied at all.
I've tried variations including adding the @Filter annotation to the getNarratives() method only and adding the @Filter annotation to the Narrative class only. I've also tried putting the @FilterDef annotation on the Topic class instead of the Narrative class. None of these variations has given the desired result: only one narrative returned from the getNarratives() method. If anyone has an example that works I would greatly appreciate it. I have concentrated on using annotations and have not yet resorted to using an xml mapping file instead. I am coding with Java 1.6, Hibernate 3.2, and MySql 5.0.51a using Eclipse 3.4 and testing with JUnit 4.
|