hibernate filters

Posted: June 19, 2012 in Hibernate

A filter in the HB provides environment to pass conditions of the persistent logic from outside the java sources through HB mapping file. A HB filter is a global, named, parameterized filter representing conditions like where clause. Having the ability of enabling or disabling them for a particular Hibernate Session.

Working with filters is nothing but making the conditions of the queries coming to application through hibernate mapping file.

Filters of hibernate are introduced from Hibernate 3.x version.

Steps to work with HB Filters to filter the data through the restrictions:

1)Define filter having parameters in Hibernate mapping file

<hibernate-mapping>

<class>

……

……

</class>

<filter-def name=”myfilter”>

<filter-param name=”myid1″ type=”integer”/>

<filter-param name=”myid2″ type=”integer”/>

</filter-def>

</hibernate-mapping>

2)link/configure filter with Hibernate pojo class through the Hibernate mapping file.

<hibernate-mapping>

<class>

……

……

<filter name=”myfilter” condition=”vendorid >= :myid1 and vendorid &lt;= :myid2″></filter>

</class>

<filter-def name=”myfilter”>

<filter-param name=”myid1″ type=”integer”/>

<filter-param name=”myid2″ type=”integer”/>

</filter-def>

</hibernate-mapping>

3)Enable filter on Hibernate Session Object and supplies values for filter parameters.

Filter filter = session.enableFilter(“myfilter”);

filter.setParameter(“myid1”,new Integer(3));

filter.setParameter(“myid2”,new Integer(5));

following resources are needed .

I) vendormaster table

CREATE TABLE `vendormaster` (
`vendorid` int(20) NOT NULL AUTO_INCREMENT,
`vendorname` varchar(50) DEFAULT NULL,
`vendoraddress` varchar(500) NOT NULL,
`vendorphone` varchar(20) NOT NULL,
`vendoremail` varchar(50) DEFAULT NULL,
PRIMARY KEY (`vendorid`)
)

Table having following records:

vid  name      address                        phone                        email

2       aaaa       sivalayam streets    9030211179               prem@gmail.com
3       bbbb      street                           9089786645              ppprr@gmail.com
4      cccc        cstreet                        9030211179               cccc@gmail.com
5      dddd       dstreet                        986624636               gopi.reshu@gmail.com

2) Vendormaster.java (pojo class)

public class Vendormaster implements java.io.Serializable {

private Integer vendorid;
private String vendorname;
private String vendoraddress;
private String vendorphone;
private String vendoremail;

public Vendormaster() {
}

public Vendormaster(String vendoraddress, String vendorphone) {
this.vendoraddress = vendoraddress;
this.vendorphone = vendorphone;
}

public Vendormaster(String vendorname, String vendoraddress,
String vendorphone, String vendoremail) {
this.vendorname = vendorname;
this.vendoraddress = vendoraddress;
this.vendorphone = vendorphone;
this.vendoremail = vendoremail;

}

public Integer getVendorid() {
return this.vendorid;
}

public void setVendorid(Integer vendorid) {
this.vendorid = vendorid;
}

public String getVendorname() {
return this.vendorname;
}

public void setVendorname(String vendorname) {
this.vendorname = vendorname;
}

public String getVendoraddress() {
return this.vendoraddress;
}

public void setVendoraddress(String vendoraddress) {
this.vendoraddress = vendoraddress;
}

public String getVendorphone() {
return this.vendorphone;
}

public void setVendorphone(String vendorphone) {
this.vendorphone = vendorphone;
}

public String getVendoremail() {
return this.vendoremail;
}

public void setVendoremail(String vendoremail) {
this.vendoremail = vendoremail;
}

}

3) Vendormaster.hbm.xml

<hibernate-mapping>
<class name=”com.shal.model.Vendormaster” table=”vendormaster” catalog=”cismysqldb”>
<id name=”vendorid” type=”java.lang.Integer”>
<column name=”vendorid” />
<generator class=”identity” />
</id>
<property name=”vendorname” type=”string”>
<column name=”vendorname” length=”50″ />
</property>
<property name=”vendoraddress” type=”string”>
<column name=”vendoraddress” length=”500″ not-null=”true” />
</property>
<property name=”vendorphone” type=”string”>
<column name=”vendorphone” length=”20″ not-null=”true” />
</property>
<property name=”vendoremail” type=”string”>
<column name=”vendoremail” length=”50″ />
</property>
<filter name=”myfilter” condition=”vendorid >= :myid1 and vendorid &lt;= :myid2″></filter>
</class>
<filter-def name=”myfilter”>
<filter-param name=”myid1″ type=”integer”/>
<filter-param name=”myid2″ type=”integer”/>
</filter-def>
</hibernate-mapping>

4)hibernate.cfg.xml

<hibernate-configuration>
<session-factory>
<property name=”connection.useUnicode”>true</property>
<property name=”connection.characterEncoding”>UTF-8</property>
<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”connection.url”>jdbc:mysql://localhost/test</property>
<property name=”connection.username”>gopal</property>
<property name=”connection.password”>gopal</property>
<property name=”show_sql”>false</property>
<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>
<property name=”current_session_context_class”>thread</property>
<property name=”hibernate.transaction.factory_class”>org.hibernate.transaction.JDBCTransactionFactory</property>
<mapping resource=”com/shal/model/Vendormaster.hbm.xml”/>
</session-factory>
</hibernate-configuration>

5) HibernateUtil.java (for Session —–> Singleton class) 

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory()
{
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println(“Initial SessionFactory creation failed.” + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

6) Mymain.java

public class Mymain {
public static void main(String[] args)throws Exception {

Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction().begin();
Filter filter = session.enableFilter(“myfilter”);
filter.setParameter(“myid1”,new Integer(3));
filter.setParameter(“myid2”,new Integer(5));
try
{
Query query = session.createQuery(“from Vendormaster”);
List list = query.list();
Iterator iterator = list.iterator();
while(iterator.hasNext())
{
Vendormaster vendormaster = (Vendormaster) iterator.next();
System.out.println(“Vendor Id is “+vendormaster.getVendorid());
}

}catch(Exception e){
e.printStackTrace();
}
session.disableFilter(“myfilter”);
System.out.println(“\n\n”);
System.out.println(“\n\n”);

try
{
Query query = session.createQuery(“from Vendormaster”);
List list = query.list();
Iterator iterator = list.iterator();
while(iterator.hasNext())
{
Vendormaster vendormaster = (Vendormaster) iterator.next();
System.out.println(“Vendor Id is “+vendormaster.getVendorid());
}

}catch(Exception e){
e.printStackTrace();
}
}

}

 

Output:

Vendor Id is 3
Vendor Id is 4
Vendor Id is 5

 

 
Vendor Id is 2
Vendor Id is 3
Vendor Id is 4
Vendor Id is 5

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s