Skip to content

Hibernate Query Language (HQL)

  • Language for querying objects
  • Similar in natural to SQL
public class QueryStudentDemo {
    public static void main(String[] args) {

        // create session factory
        SessionFactory factory = new Configuration()
                            .configure("hibernate.cfg.xml") // Config file
                            .addAnnotatedClass(Student.class) // Class with the field mapping
                            .buildSessionFactory(); // build the factory

        // create a session
        Session session = factory.getCurrentSession();

        try {
            // begintransaction
            session.beginTransaction();

            // query students
            List<Student> theStudents = session.createQuery("from Student").getResultList();
            List<Student> theStudents2 = session.createQuery("from Student s WHERE s.lastName='Vitoi'").getResultList(); // use the "lastname" from entity, not "last_name" from column name
            List<Student> theStudents3 = session.createQuery("from Student s WHERE s.lastName='Vitoi' OR s.firstName='Daffy'").getResultList();
            List<Student> theStudents4 = session.createQuery("from Student s WHERE s.email LIKE '%mail.com'").getResultList();

            displayStudents(theStudents);
            displayStudents(theStudents2);
            displayStudents(theStudents3);
            displayStudents(theStudents4);

            // commit transaction
            session.getTransaction().commit();
            System.out.println("Done!");
        }
        finally {
            factory.close();
        }
    }

    private static void displayStudents(List<Student> theStudents) {
        for (Student student: theStudents) {
            System.out.println(student);

        }
    }
}
session.beginTransaction();

// build query
Query<Instructor> query = session.createQuery(
        "SELECT i from Instructor i " + "JOIN FETCH i.courses " + "WHERE i.id=:instructorId", Instructor.class);

// set query parameter
query.setParameter("instructorId", 1);

// execute query
Instructor instructor = query.getSingleResult();

// get courses
System.out.println("Instructor: " + instructor);

// done
session.getTransaction().commit();
System.out.println("Done!");

CRUD Operations

Create

public class CreateStudentDemo {
    public static void main(String[] args) {

        // create session factory
        SessionFactory factory = new Configuration()
                            .configure("hibernate.cfg.xml") // Config file
                            .addAnnotatedClass(Student.class) // Class with the field mapping
                            .buildSessionFactory(); // build the factory

        // create a session
        Session session = factory.getCurrentSession();

        try {
            System.out.println("Creating 3 student objects...");

            // create student objects
            Student tempStudent1 = new Student("Henry", "Vitoi", "[email protected]");
            Student tempStudent2 = new Student("Martin", "Applebaum", "[email protected]");
            Student tempStudent3 = new Student("Luther", "Santos", "[email protected]");

            // start transaction
            session.beginTransaction();

            // save student object
            System.out.println("Saving student...");
            session.save(tempStudent1);
            session.save(tempStudent2);
            session.save(tempStudent3);

            // commit transaction
            session.getTransaction().commit();
            System.out.println("Done!");
        }
        finally {
            factory.close();
        }
    }
}

Read

public class ReadStudentDemo {
    public static void main(String[] args) {

        // create session factory
        SessionFactory factory = new Configuration()
                            .configure("hibernate.cfg.xml") // Config file
                            .addAnnotatedClass(Student.class) // Class with the field mapping
                            .buildSessionFactory(); // build the factory
        Session session;

        try {
            /*
            ** CREATE AND SAVE STUDENT
             */
            System.out.println("Creating a new student object...");

            // create a session
            session = factory.getCurrentSession();

            // create student object
            Student student = new Student("Daffy", "Duck", "[email protected]");

            // start transaction
            session.beginTransaction();

            // save student object
            System.out.println(student);
            session.save(student);

            // commit transaction
            session.getTransaction().commit();
            System.out.println("Student saved! Generated ID: " + student.getId());

            /*
             ** READ STUDENT
             */
            System.out.println("\nSearching for student...");

            // create a session
            session = factory.getCurrentSession();

            // start transaction
            session.beginTransaction(); // The query is also a transaction! In hibernate world everything is a transaction

            // get student
            System.out.println("Getting student with ID: " + student.getId());
            Student foundStudent = session.get(Student.class, student.getId()); // Search based on primary key. Returns null if not found
            System.out.println("Student found: " + foundStudent);

            // commit transaction
            session.getTransaction().commit(); // transactions must be committed even for reading
            System.out.println("Done");

        }
        finally {
            factory.close();
        }
    }
}

Update

public class UpdateStudentDemo {
    public static void main(String[] args) {

        // create session factory
        SessionFactory factory = new Configuration()
                            .configure("hibernate.cfg.xml") // Config file
                            .addAnnotatedClass(Student.class) // Class with the field mapping
                            .buildSessionFactory(); // build the factory

        Session session = factory.getCurrentSession();

        try {
            int studentId = 1;

            // begin transaction
            session.beginTransaction();

            // get student
            System.out.println("\nGetting student with id: " + studentId);
            Student myStudent = session.get(Student.class, studentId);
            System.out.println("Get complete: " + myStudent);

            // update student
            System.out.println("Updating student...");
            myStudent.setFirstName("Scooby");
            System.out.println("updating all student emails...");
            session.createQuery("UPDATE Student SET email='[email protected]'").executeUpdate();

            // commit transaction
            session.getTransaction().commit();
            System.out.println("Done!");
        }
        finally {
            factory.close();
        }
    }
}

Delete

public class DeleteStudentDemo {
    public static void main(String[] args) {

        // create session factory
        SessionFactory factory = new Configuration()
                            .configure("hibernate.cfg.xml") // Config file
                            .addAnnotatedClass(Student.class) // Class with the field mapping
                            .buildSessionFactory(); // build the factory

        Session session = factory.getCurrentSession();

        try {
            int studentId = 1;

            // begin transaction
            session.beginTransaction();

            // get student
            System.out.println("\nGetting student with id: " + studentId);
            Student myStudent = session.get(Student.class, studentId);
            System.out.println("Get complete: " + myStudent);

            // delete student
            System.out.println("Deleting student #1: " + myStudent);
            session.delete(myStudent);
            System.out.println("Deleting student #2");
            session.createQuery("DELETE from Student WHERE id=2").executeUpdate();

            // commit transaction
            session.getTransaction().commit();
            System.out.println("Done!");
        }
        finally {
            factory.close();
        }
    }
}