hibernate Criterias and Projections Use Filters


Example

@Filter is used as a WHERE camp, here some examples

Student Entity

@Entity
@Table(name = "Student")
public class Student
{
    /*...*/

    @OneToMany
    @Filter(name = "active", condition = "EXISTS(SELECT * FROM Study s WHERE state = true and s.id = study_id)")
    Set<StudentStudy> studies;

    /* getters and setters methods */
}

Study Entity

@Entity
@Table(name = "Study")
@FilterDef(name = "active")
@Filter(name = "active", condition="state = true")
public class Study
{
    /*...*/

    @OneToMany
    Set<StudentStudy> students;

    @Field
    boolean state;

    /* getters and setters methods */
}

StudentStudy Entity

@Entity
@Table(name = "StudentStudy")
@Filter(name = "active", condition = "EXISTS(SELECT * FROM Study s WHERE state = true and s.id = study_id)")
public class StudentStudy
{
    /*...*/

    @ManytoOne
    Student student;

    @ManytoOne
    Study study;

    /* getters and setters methods */
}

This way, everytime the "active" filter is enabled,

-Every query we do on the student entity will return ALL Students with ONLY their state = true studies

-Every query we do on the Study entity will return ALL state = true studies

-Every query we do on the StudentStudy entiy will return ONLY the ones with a state = true Study relationship

Pls note that study_id is the name of the field on the sql StudentStudy table