devxlogo

Write a Complex Query in Hibernate

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();      }}

devx-admin

Share the Post: