Java Hibernate (II): Hibernate Query Language (HQL)

Today we are going to start to job with Hibernate, we will make a class for every tipe : Select, Insert, Update and Delete data for our database.

First of all remember, we need a SessionFactory class to start our sessions :

package Class;
/// @author Start2Develop
 
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SessionFactoryUtil {
    
 //Factory class with method
    private static final SessionFactory sessionFactory = 
            new Configuration().configure("/connection/hibernate.cfg.xml").buildSessionFactory();

    public static SessionFactory getSessionFactory(){
 return sessionFactory;
 }}

SELECT statement retrieves zero or more rows from one or more database tables or database views.

Every time we work with Hibernate we need to open a new sesion calling our SessionFactoryUtil class.

With the connection up, we make a new query object type, then iterate our Student maped class with getters.

package Class;
import java.util.*;
import model.Students;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class SelectStudents {
public static void main(String[] args) {

SessionFactory generalSesion = SessionFactoryUtil.getSessionFactory();
//Open session
 Session sesion = generalSesion.openSession();

 Query q = sesion.createQuery("from Students"); 
 List<Students> studentList = q.list();

 //Iterate our student list
 System.out.println("===========================================");
 System.out.println("Students table");
 System.out.println("===========================================");

 for(Students actual_student : studentList){
 System.out.println(" codStudents : " +
actual_student.getCodStudent()+ " name :" + actual_student.getName()+
         " || lastName :" +actual_student.getLastName()+" || mark : "+actual_student.getMark()); }

 System.out.println("===========================================");
 sesion.close();}}

The program will display the data from the Students table  :

================================================================

To insert data to an specific table , its similar than select , but we need begin a new transaction object.

Then add the new Student row using the constructor, save and commit the changes.

Remember to use try-catch blocks to handle exceptions and a rollback – transaction method to make more safetly the database changes, and after all, close session.

package Class;


import model.Students;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class InsertStudents {
 public static void main(String[] args) {

 //1.- New Session to work with hibernate
 //We open the session and start a new transaction for the insertion operation
 SessionFactory generalSesion =
SessionFactoryUtil.getSessionFactory();
 Session sesion = generalSesion.openSession();

 //2.- We associate a transaction to the session
 Transaction tx = sesion.beginTransaction();
 try{
 System.out.println("Insert new row in Students table");

 //New object students to insert 
 //  public Students(int codStudent, String name, String lastName, Float mark)
 Students st = new Students(4,"Helen","Berry",Float.parseFloat("8.5"));

 sesion.save(st); //Save new object in the Database
 tx.commit(); //We make the commit so that the changes are effective in the data model
 }
 catch(Exception ex){
 tx.rollback();
 ex.getCause();
 }

 //Close sessions
 sesion.close();
 }
}

================================================================

Now,  lets see an update class using  HQL query, like Select and Update, we need open a new sesion.

In this example we update all student marks lower than five , to five with the clausure WHERE. We need to iterate the Students rows and call Setters , then use update SessionFactory method.

Finally commit, rollback and close session.

package Class;
import java.util.List;
import model.Students;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
//Remember try-catch 
public class UpdateStudents {
 public static void main(String[] args) {
 
     SessionFactory generalSesion = SessionFactoryUtil.getSessionFactory();
 //We opened the session and started a new transaction for the insertion operation
 Session sesion = generalSesion.openSession();
 //
 Query q = sesion.createQuery("from Students WHERE mark <5");
 //Start the transaction
 Transaction tx = sesion.beginTransaction();
 try{
 List<Students> studentList = q.list();
 System.out.println("New mark");
 for (Students actual_student : studentList) {
 actual_student.setMark(Float.parseFloat("5.00"));
 sesion.update(actual_student);
 }
 //Finish the transaction
 tx.commit();
 }
 catch(Exception e){
 //Undo the transaction
 tx.rollback();
 }
 finally{
 sesion.close();
 }}}

================================================================

As you can see, all class are similar, we just need to change query to delete data from our database , with the next example we delete all rows where Students marks = than five:

package Class;
import model.Students;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import java.util.*;
import org.hibernate.Session;
public class DeleteStudents {
 public static void main(String[] args) {
     
 SessionFactory generalSesion = SessionFactoryUtil.getSessionFactory();
 //We open the session and start a new transaction for the delete operation
 Session sesion = generalSesion.openSession();
 Query q = sesion.createQuery("from Students where mark =5");
 //Start the transaction
 Transaction tx = sesion.beginTransaction();
 try{
 List<Students> studentList = q.list();
 
 for (Students actual_student : studentList) {
 sesion.delete(actual_student);
 System.out.println("Student Deleted");
 }
 //ffinish transaction
 tx.commit();
 }
 catch(Exception e){
 tx.rollback();
 }
 finally{
 sesion.close();
 }}}

Feel free to take and modify this code :

https://github.com/RayRT/JavaHibernateHQL

If you want more Hibernate and HQL documentation :

Hibernate documentation

Hibernate HQL 

Acerca del autor: Start2Develop

Dejar una contestacion

Tu dirección de correo electrónico no será publicada.