Friday, January 16, 2015

Hibernate Filter Example



Hibernate Filter
I am going to describe very basic thing about hibernate data filter for pre-define fetching of data.
Just consider any application,in which on every page or listing we only fetch data those are not deleted, i.e isDeleted=false.
We fetch such data by writting criteria or HQL using WHERE clause or Criteria Restrictions.
But at the same time we have to apply  this on associated child collection then we Iterate on the dependent association  to make sure that the record is deleted or not, and then it becomes very costly.
To override such kind of problem we can use hibernate filter and as per our need we can enable or disable it.
See below filter configuration
HBM configuration
<hibernate-mapping>
 
<class name="Users" table="userdetails" >

<filter name="deleteCheck" condition="isDeleted = :deleteFlag"/>
</class>   
 
 <filter-def name=" deleteCheck ">
   <filter-param name=" deleteFlag" type="boolean"/>
 </filter-def>
</hibernate-mapping>

Annotation Configuration

@javax.persistence.Entity(name="userdetails")

@FilterDef(name="deleteCheck",parameters=@ParamDef( name="deleteFlag", type="boolean" ))
@Filter(name="deleteCheck", condition="isDeleted=:deleteFlag")

public class User implements Serializable {
     
      private static final long serialVersionUID = 1L;
     
      private Integer userId;
     
      private String name;
     
      private String address;
     
      private Boolean isDeleted;
     
           
      //Setter getter method

}


Applying Filter

public List getUsers()
      {
            List userlist=null;
            Session session=HibernateSessionFactory.getSession();
            session.enableFilter("deleteCheck").setParameter("deleteFlag",true);
//session.disableFilter("deleteCheck");
            Criteria crit=session.createCriteria(User.class);
            userlist=crit.list();
            session.flush();
            session.close();
System.out.println(userList.size()+" user records");
            return userlist;
      }

It will automatically filter the data according to your filter param there is no need to do anything additional.


@Note: We can also apply this filter on collections or association as follows

For more details on Hibernate Filter Click here


No comments:

Post a Comment

Spring Boot Config Server and Config Client.

 In Spring cloud config we can externalise our configuration files to some repository like GIT HUT, Amazon S3 etc. Benefit of externalising ...