Saifer
Saifer

Reputation: 380

Hibernate Entity @Filter relationship

I've got 3 Entity, 1 for study, 1 for students and 1 called studentStudy that is the relationship between the first two, with additional informatios.

What I need is that when a study is disabled, studentStudy is hidden as well, I need to do this with the @Filter and @FilterDef but it doesn't works.

Student Entity

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

    @OneToMany
    @Filter(name = "active")
    Set<StudentStudy> studies;

    /* getters and setters methods */
}

Study Entity

@Entity
@Table(name = "Study")
@FilterDef(name = "active")
@Filters{
    /*...*/
    @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")
public class StudentStudy
{
    /*...*/

    @ManytoOne
    Student student;

    @ManytoOne
    Study study;

    /* getters and setters methods */
}

When I enable the "active" filter actually, study entity queries hide the inactive ones

I want to apply the filter on Study also in Student queries, hiding the StudentStudy related. I readed that a way is to use annotation @Filter on the field @OnetoMany, but it actually doesn't works

Upvotes: 1

Views: 4546

Answers (1)

Saifer
Saifer

Reputation: 380

I resolved adding a @Filter as a WHERE camp of my query, updates tables are these

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

Upvotes: 2

Related Questions