在session.get()的情况下,hibernate过滤器不起作用,但在session.createQuery()的情况下工作

时间:2016-11-07 16:11:23

标签: java spring hibernate

我正在使用hibernate 4.我正在编写一个过滤器。我注意到的一件奇怪的事情是,如果我使用session.get()方法

,则不会应用过滤器
public SecurityAgency getSecurityAgencyById(int id) {
        Session session = this.sessionFactory.getCurrentSession();
        session.enableFilter("byEnabled");
        SecurityAgency s = (SecurityAgency)session.get(SecurityAgency.class, new Integer(id));

         return s;
    }

只要用session.createQuery方法替换session.get方法并发送HQL查询,过滤器就会开始工作。我在hibernate文档中找不到任何这种行为的原因。

安全机构类中的过滤声明

@Entity
@Table(name="security_agency")

public class SecurityAgency  implements java.io.Serializable {
 @Id
 @Column(name = "id")
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private int id;
 @Column(name="name")
 private String name;
 @Column(name="code")
 private String code;
 @Column(name="website")
 private String website;
 @Column(name="tan")
 private String tan;
 @Column(name="email")
 private String email;
 @Column(name="pan")
 private String pan;
 @Column(name="created_at")
 private Date createdAt;
 @Column(name="created_by")
 private long createdBy;
 @Column(name="modified_at")
 private Date modifiedAt;
 @Column(name="modified_by")
 private long modifiedBy;
 @OneToMany(mappedBy="securityAgency",fetch = FetchType.EAGER)
 @JsonIgnoreProperties("securityAgency")

 @Filter(name = "byEnabled", condition = "is_enabled= 1")
 private Set<ContactPerson> contactPersons = new HashSet<ContactPerson>(0);

public SecurityAgency() {
}

联系人类

@Entity
@Table(name = "contact_person")
@FilterDefs({
    @FilterDef(name="byEnabled"),
    @FilterDef(name="bySecurityAgency",parameters =       @ParamDef(name="agency_id", type="int"))
})
@Filters({
    @Filter(name="byEnabled", condition = "is_enabled = 1"),
    @Filter(name="bySecurityAgency", condition = "agency_id= :agency_id ")
})
public class ContactPerson  implements java.io.Serializable {

2 个答案:

答案 0 :(得分:2)

如果使用id值获取,则过滤器不起作用。请使用Query接口。见this thread

答案 1 :(得分:1)

如果要使用表列值,则需要使用过滤器连接表(@FilterJoinTable),@ Filter应用于目标实体而不是表

试,

@FilterJoinTable(name = "byEnabled", condition = "is_enabled= :enabled")
private Set<ContactPerson> contactPersons = new HashSet<ContactPerson>(0);

获取

 session.enableFilter("byEnabled").setParameter("enabled",  Integer.valueOf(1));