Hibernate Introduction Part 4

 

This article is a continuation of our previous article.

In the previous post, we have seen how to retrieve all the records in the database. But most of time, this is not the case.  Sometime we need to retrieve particular record by passing the primary key.

Say for example, in SQL

Select * from User where UserID=’John’

This can be achieved in HQL using Variable injection option

And also , When we expect multiple rows, then we know what we can use Query’s List method() as we seen in the previous example. On the other hand, When we expect a single record, then we can use Query’s  uniqueResult()

 

Here is the full code for the Method to retrieve the unique record

 

public static void getPatientByID(int anyvalue) {

    try {
        Configuration configuration = new Configuration();
        configuration.configure();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(
                configuration.getProperties()).buildServiceRegistry();
        factory = configuration.buildSessionFactory(serviceRegistry);
    } catch (Throwable ex) {
        System.err.println("Failed to create sessionFactory object." + ex);
        throw new ExceptionInInitializerError(ex);
    }
    System.out.println("**Example : Hibernate  SessionFactory**");
    System.out.println("----------------------------------------");
   
    Session session = factory.openSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        Query q1 = session.createQuery("from patient where id =:idvalue");
        q1.setInteger("idvalue", anyvalue);
        Object queryResult = q1.uniqueResult();
        patient p1 = (patient)queryResult;
        tx.commit();
        System.out.print(p1.getLastName());
    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }
}

 

Here is the updated test.java code

package mypack;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.HibernateException;

public class Test {

    private static SessionFactory factory;
    private static ServiceRegistry serviceRegistry;

    public static void main(String[] args) {
        createRecords();
        getAllRecords();
        getPatientByID(1);
        getPatientByID(13);
       
    }

    public static void createRecords() {

        try {
            Configuration configuration = new Configuration();
            configuration.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(
                    configuration.getProperties()).buildServiceRegistry();
            factory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }
        System.out.println("**Example : Hibernate 4 SessionFactory**");
        System.out.println("----------------------------------------");

        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            patient pt = new patient();
            pt.setFirstName("John12");
            pt.setLastName("Smith23");
            session.saveOrUpdate(pt);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
   
    public static void getAllRecords() {

        try {
            Configuration configuration = new Configuration();
            configuration.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(
                    configuration.getProperties()).buildServiceRegistry();
            factory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }
        System.out.println("**Example : Hibernate  SessionFactory**");
        System.out.println("----------------------------------------");
       
        List allpatients;
       
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Query q1 = session.createQuery("from patient");
            allpatients = q1.list();
            for (int i =0; i < allpatients.size(); i++)
            {
                patient pt = (patient) allpatients.get(i);
                System.out.println(pt.getLastName());
            }
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

   
    public static void getPatientByID(int anyvalue) {

        try {
            Configuration configuration = new Configuration();
            configuration.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(
                    configuration.getProperties()).buildServiceRegistry();
            factory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }
        System.out.println("**Example : Hibernate  SessionFactory**");
        System.out.println("----------------------------------------");
       
       
       
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Query q1 = session.createQuery("from patient where id =:idvalue");
            q1.setInteger("idvalue", anyvalue);
            Object queryResult = q1.uniqueResult();
            patient p1 = (patient)queryResult;
            tx.commit();
            System.out.print(p1.getLastName());
        } catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

}