Hibernate Filters
Hibernate Filters allows the Programmer to specify
pre-defined criteria/condition for the persistence logic of hibernate
programming
Filters represent where condition clause related
conditions in hibernate mapping file and they are visible for multiple session
objects of hibernate applications. These filters can be enabled or disabled
dynamically at runtime on each session object level.
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:xe</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">system123</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<mapping resource="emp.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Mapping File(emp.hbm.xml)
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="emp1" table="emp">
<id name="empno" column="empno">
</id>
<property name="ename" column="ename" type="string" length="25"></property>
<property name="sal" column="sal" type="int" not-null="true"></property>
<filter name="myfilter" condition="empno>=:myid1 and empno <=:myid2"></filter>
</class>
<filter-def name="myfilter">
<filter-param name="myid1" type="int"/>
<filter-param name="myid2" type="int"/>
</filter-def>
</hibernate-mapping>
POJO Class(emp1.java)
public class emp1 {
private int empno,sal;
private String ename;
Setter and Getter Methods
}
Client.java
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Filter;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
public class client {
public static void main(String arg[]) throws Exception
{
Configuration cfg=new Configuration();
cfg=cfg.configure("hibernate.cfg.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Filter f=s.enableFilter("myfilter");
f.setParameter("myid1", 1);
f.setParameter("myid2", 6);
Query q=s.createQuery("From emp1");
List<emp1> l=q.list();
for(int i=0;i<l.size();i++)
{
emp1 obj=(emp1)l.get(i);
System.out.println("empno is "+obj.getEmpno());
}
s.clear();
sf.close();
System.out.println("finished is");
}
}
No comments:
Post a Comment