Hibernate Data filtering
1, data filtering can be understood as a special way of data query, this is a whole data filtering method, once the data filter is enabled, the filter will automatically act on the specified scope, only the data to meet the filter record can be selected, from this point of view, Hibernate provides a data filtering mechanism, Can be regarded as an auxiliary means of conditional query; 2. Hibernate provides the following annotations to support filter @FilterDef: Configure filters, @Filter: Apply filters;
3. Use examples The following example configures 2 filters, a global filter, and a local filter User.java
/* 2 Filter Filters Effectiveage: Global filter For filtering the Age property, filter effectivedate: Local filter For filtering the CreateDate attribute of the associated entity comment *// Configures the parameter type of the filter associated with user @FilterDefs ({@FilterDef (name = "Effectivedate",//filter name "E Ffectivedate "parameter list parameters = {@ParamDef (name =" Datelimit ", type =" date ")}),//The filter contains a parameter" Datelimit ", type is date @FilterDef (name =" Effectiveage ", parameters = {@ParamDef (name =" Agelimit ", type =" int ")}) @Entity @Table (name=" users ") @Filter (name=" effectiveage ", condition =" Age >=: Agelimit ")//Global filter Effectivea
GE public class User {@Id @Column (name= "user_id") private int Id;
@Column (name= "user_name") private String name;
@Column (name= "User_age") private String age; @OneToMany (targetentity = Comment.class,cascade=cascadetype.all,mappedby = "user") @Filter (name= "Effectivedate", Condition = "CreateDate >=:d atelimit")//local filter effectivedate private set< comment> comments = new hashset<> ();
Test.java
public class Test {public
static void Main (string[] args) throws exception{
Session session = Hibernateutil.curr Entsession ();
Transaction tran = Session.begintransaction ();
Start two filters and configure the parameter
session.enablefilter ("Effectivedate")
. Setparameter ("Datelimit", New SimpleDateFormat ("Yyyy-mm-ss"). Parse ("2016-01-01"));
Session.enablefilter ("Effectiveage")
. Setparameter ("Agelimit");
List List = Session.createquery ("Select u from Users u")
. List ();
Tran.commit ();
Hibernateutil.closesession ();
}
}