Reputation: 789
I am using hibernate 4. I am writing a filter. The strange thing I noticed is the filter is not getting applied if I use session.get() method
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;
}
Filter starts working as soon as I replace the session.get method with session.createQuery method and send a HQL query. I am unable to find any reason for this behaviour in the hibernate documentation.
FIlter declaration in securtiy agency class
@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() {
}
Contact person class
@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 {
Upvotes: 2
Views: 2619
Reputation: 272
Filter doesn't work if you are fetching using id value.Use Query interface instead. See this thread
Upvotes: 2
Reputation: 11037
if you want to use table column values you need to use filter join table ( @FilterJoinTable ), @Filter is applied to target entity rather than table
try,
@FilterJoinTable(name = "byEnabled", condition = "is_enabled= :enabled")
private Set<ContactPerson> contactPersons = new HashSet<ContactPerson>(0);
get
session.enableFilter("byEnabled").setParameter("enabled", Integer.valueOf(1));
Upvotes: 1