|
So far we have seen how to use HQL and native SQL to perform certain database operations. We saw that the HQL was much simpler than the native SQL as we had to provide database columns and the mapping attributes along with mapping classes too to get fully translated java objects in native SQL. Hibernate provides much simpler API called Criteria Queries if our intention is only to filter the objects or narrow down the search. In Criteria Queries,we don't need to provide the select or from clause. Instead,we just need to provide the filtering criteria. For example name like '%a',or id in (1,2,3) etc. Like HQL,the Criteria API works on java objects instead on database entities as in case of native SQL.
Let's write a method in UserManager to filter the users that have user id within a set of passed user id's.
public java.util.List getUserByCriteria(Long[] items)
{
org.hibernate.Criteria criteria = session.createCriteria(User.class);
criteria.add(org.hibernate.criterion.Restrictions.in("userId", items));
return criteria.list();
}
This method returns the users and associated phone numbers that have one of the user id in items passed as an argument. See how a certain filter criteria is entered using Restrictions class. Similarly we can use Restrictions.like,Restrictions.between,Restrictions.isNotNull,Restrictions.isNull and other methods available in Restrictions class.
Let's write the test code to verify that the filter we provided using Criteria works. Add the following method in TestClient.
public void testFindByCriteria(UserManager manager)
{
java.util.Iterator users = manager.getUserByCriteria(new Long[]{new Long(1),new Long(2)}).iterator();
while(users.hasNext())
{
User user = (User)users.next();
System.out.println("User found with ID="+user.getUserId()+"\n" +
"\tName="+user.getLastName()+"\n" +
"\tEmail="+user.getEmail() +
"");
java.util.Iterator numbers = user.getPhoneNumbers().iterator();
while(numbers.hasNext()) {
PhoneNumber phone = (PhoneNumber)numbers.next();
System.out.println("\t\tNumber Type:"+phone.getNumberType()+"\n" +
"\t\tPhone Number:"+phone.getPhone());
}
}
}
Add the call to this method in main. To do this,add the following line in main. client.testFindByCriteria(manager);
We passed the two user ids to the function. So we should get the two users (if we have in the database with these user id's) with appropriate phone number entries if they exist in the database. Here is what gets displayed under my environment. You should adjust the appropriate user id's to get the results.
User found with ID=1
Name=Elison
Email=john@visualbuilder.com
Number Type:Office
Phone Number:934757
Number Type:Home
Phone Number:934757
User found with ID=2
Name=Elison
Email=john@visualbuilder.com
Number Type:Home
Phone Number:934757
Number Type:Office
Phone Number:934757
|