Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Advanced
Apr 10, 2009

Write a Complex Query in Hibernate

This tip shows you how to use the findByExample method in Hibernate. The method uses the SQL AND operator to log in a user given an email address and password. This code assumes you have a database table named Accountse mapped in the com.extensions.Accountse class:

/**
 * Get the list with the right account
 * 
 * @param instance
 * @param c_email
 * @param c_password
 * @return List
 * @throws Exception 
 */
public List findByExampleAnd(String c_email, 
   String c_password)
   throws java.lang.Exception 
{
   
   log.info("Finding Accountse instance by example...");      
   Session session = HibernateUtil.currentSession();

   try {
      List results =  
         session.createCriteria(
            "com.extensions.Accountse").add(     
            Restrictions.and(Restrictions.eq(
            "email",c_email), 
            Restrictions.eq("password",c_password))).list();
                   
     log.info("Find by example successful, result size:  " + 
        results.size());
      
     return results;
      
   } catch (Exception re) {
        log.error("Find by example failed...", re);
        throw re;
   } finally {
        HibernateUtil.closeSession();   
   }
}
Leonard Anghel
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap