Hibernate实体@Filter关系

时间:2016-06-09 11:29:37

标签: java spring hibernate

我有3个实体,1个用于学习,1个用于学生,1个叫做studentStudy,这是前两个之间的关系,还有其他信息。

我需要的是,当一项研究被禁用时,studentStudy也会被隐藏,我需要使用@Filter和@FilterDef执行此操作,但它不起作用。

学生实体

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

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

    /* getters and setters methods */
}

研究实体

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

    @ManytoOne
    Student student;

    @ManytoOne
    Study study;

    /* getters and setters methods */
}

当我启用&#34;有效&#34;实际过滤,研究实体查询隐藏不活动的查询

我想在Student查询中应用过滤器,同时隐藏StudentStudy。我认为一种方法是在@OnetoMany字段上使用注释@Filter,但它实际上不起作用

1 个答案:

答案 0 :(得分:1)

我决定添加@Filter作为我的查询的WHERE阵营,更新表是这些

学生实体

@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 */
}

研究实体

@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
@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 */
}

这样,每次&#34;活跃&#34;过滤器已启用,

- 我们对学生实体进行的每次查询都将返回所有学生他们的state = true学习

- 我们在Study实体上执行的每个查询都将返回所有 state = true项研究

- 我们对StudentStudy entiy进行的每个查询都将返回具有state = true学习关系的

请注意,study_id是sql StudentStudy表中字段的名称