Filters

In the previous chapter, we showed you how to apply filters using annotation. Another way is to apply filters to a collection that is already in the persistence context. This is quite useful to fetch only a subset of a collection.

For example, if you have a list of teachers and their students in the database and you are simply interested in fetching the records for all the female students, you can use filters, which can be very efficient in some cases.

To demonstrate how to use filters, let's assume that we have the following entities:

@Entity
public class Teacher {
  @Id
  @GeneratedValue
  private long id;
  private String name;
  
  @OneToMany(cascade=CascadeType.ALL)
  Set<Student> students = new HashSet<Student>();
  // getters and setters
}

@Entity
public class Student {
  @Id
  @GeneratedValue
  private long id;
  private String name;
  private String gender;
  // getters and setters
}

You can get the teacher record using a simple fetch:

Teacher teach = (Teacher) session
.get(Teacher.class, teacher.getId());

At this point, as we fetched lazily, we only have the uninitialized version of the associated student entities. Of course, as soon as we try to access the student set from the teacher entity, Hibernate will fire off a SQL to get all the student records. However, we are only interested in the female students. This is how you get the records of female students using filters:

List<Student> students = session
  .createFilter(teach.getStudents(), 
     "select this where this.gender='female'")
  .list();

A few things are worth noting here. First, it doesn't matter if your root entity is set to fetch lazily or eagerly, either way the original collection, in this case students, is untouched and the result of the filter is a new collection. Second, Hibernate does not perform this in memory. It actually goes back to the database to execute an SQL for the filter. Finally, the second argument is HQL. The this special keyword refers to the element of the collection that is being acted on by the filter, in this case a student entity in the collection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.128.105