File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Object Relational Mapping and the fly likes Hibernate Filter not working Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Hibernate Filter not working" Watch "Hibernate Filter not working" New topic

Hibernate Filter not working

Pankaj Kumarkk
Ranch Hand

Joined: Apr 17, 2011
Posts: 110
I am using below code and the filter is not working

<class name="roseindia.tutorial.hibernate.Contact" table="CONTACT">
<id name="id" type="long" column="ID" >
<generator class="assigned"/>
<property name="firstName">
<column name="FIRSTNAME" />
<property name="lastName">
<column name="LASTNAME"/>
<property name="email">
<column name="EMAIL"/>
<filter name="limitByFirstName" condition=":satish='SATISH' "/>
<filter-def name="limitByFirstName">
<filter-param name="satish" type="string"/>

Java code::
Configuration cfg = new Configuration();
cfg = cfg.configure();
// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = cfg.buildSessionFactory();

session =sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Filter filter = session.enableFilter("limitByFirstName");
filter.setParameter("satish", "SATISH");

Contact contact = (Contact) session.get(Contact.class, new Long(7));
System.out.println("contact.getFirstName() :" + contact.getFirstName());

Console output:
Hibernate: select contact0_.ID as ID0_, contact0_.FIRSTNAME as FIRSTNAME0_0_, contact0_.LASTNAME as LASTNAME0_0_, contact0_.EMAIL as EMAIL0_0_ from CONTACT contact0_ where contact0_.ID=?
contact.getFirstName() eepak

I am expecting the record with "Deepak" not to come as my filter coniditon is firstname='SATISH'. Can anybody help. I see the sql doesn't also have the filter condition clause.

Pankaj Kumarkk
Ranch Hand

Joined: Apr 17, 2011
Posts: 110
I got the problem solved.
The problem was that Filter doesn't work if you are fetching using id value. I change the call from session.get to use Query interface and it is working.
Here is the changed code
Filter filter = session.enableFilter("limitByLastName");
filter.setParameter("satish", "SATISHKATARIA");
Transaction tx = session.beginTransaction();

Query query = session.createQuery("from roseindia.tutorial.hibernate.Contact");
List list = query.list();
Iterator it = list.iterator();
Contact name = (Contact);
System.out.println("name :" + name.getFirstName());

Console output:
Hibernate: select contact0_.ID as ID, contact0_.FIRSTNAME as FIRSTNAME0_, contact0_.LASTNAME as LASTNAME0_, contact0_.EMAIL as EMAIL0_ from CONTACT contact0_ where ? ='SATISH'
I agree. Here's the link:
subject: Hibernate Filter not working
It's not a secret anymore!