| Author |
Hibernate Filter not working
|
Pankaj Kumarkk
Ranch Hand
Joined: Apr 17, 2011
Posts: 108
|
|
Hi,
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"/>
</id>
<property name="firstName">
<column name="FIRSTNAME" />
</property>
<property name="lastName">
<column name="LASTNAME"/>
</property>
<property name="email">
<column name="EMAIL"/>
</property>
<filter name="limitByFirstName" condition=":satish='SATISH' "/>
</class>
<filter-def name="limitByFirstName">
<filter-param name="satish" type="string"/>
</filter-def>
</hibernate-mapping>
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());
session.close();
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.
Thanks!
|
 |
Pankaj Kumarkk
Ranch Hand
Joined: Apr 17, 2011
Posts: 108
|
|
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();
while(it.hasNext())
{
Contact name = (Contact) it.next();
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'
|
 |
 |
|
|
subject: Hibernate Filter not working
|
|
|