Open In App

Hibernate – Criteria Queries

Last Updated : 28 Mar, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc.

To get the data available in RDBMS tables, Hibernate follows one method via Criteria API. This will help you to filter the resultset as desired. i.e. exactly how we write a “WHERE” clause for a SQL, the same way it can be handled here by means of Criteria Query. The logical operation, pagination concepts, sorting concepts, aggregation concepts too supported with Criteria Query.

Implementation: Let us take a sample table in MySQL to proceed further

-- Here name of the database is geeksforgeeks
-- Name of the table is geekEmployee 
create table geeksforgeeks.geekEmployee (
   id INT NOT NULL auto_increment,
   firstName VARCHAR(20) default NULL,
   lastName  VARCHAR(20) default NULL,
   salary     INT  default NULL,
   PRIMARY KEY (id)
);

A: File: GeekEmployee.java

Primarily, let us define a “GeekEmployee” POJO class, mapping file(mapping between POJO class and geekEmployee table), configuration file(informs about MySQL as the database is taken, credentials and the mapping file that needs to be looked. 

Example:

Java




// Java Program to Illustrate GeekEmployee Class
 
// CLass
public class GeekEmployee {
 
    // Class data members
    private int id;
    private String firstName;
    private String lastName;
    private int salary;
 
    // All the four attributes must match with geekEmployee
    // table and datatypes also should match
 
    // Constructor
    public GeekEmployee() {}
 
    // Constructor
    public GeekEmployee(String firstName, String lastName,
                        int salary)
    {
 
        // This keyword refers to current instance itself
        this.firstName = firstName;
        this.lastName = lastName;
        this.salary = salary;
    }
 
    // Getters and Setters
 
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getFirstName() { return firstName; }
    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }
    public String getLastName() { return lastName; }
    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }
    public int getSalary() { return salary; }
    public void setSalary(int salary)
    {
        this.salary = salary;
    }
}


 
 

 
 

 

B: File: geekEmployee.hbm.xml (Mapping file that connects POJO class and MySQL table)

 

 

 

XML




<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
<hibernate-mapping>
  <!-- This is the place where GeekEmployee POJO class  and geekEmployee table mapping -->
   <class name = "com.geeksforgeeks.GeekEmployee" table = "geekEmployee">     
      <meta attribute = "class-description">
         This class contains the geekEmployee detail. This is optional
      </meta>
       
      <id name = "id" type = "int" column = "id">
         <generator class="native"/>
      </id>
       
      <property name = "firstName" column = "first_name" type = "string"/>
      <property name = "lastName" column = "last_name" type = "string"/>
      <property name = "salary" column = "salary" type = "int"/>
       
   </class>
</hibernate-mapping>


 
 

 
 

 

C: File: hibernate.cfg.xml (Hibernate configuration file)

 

 

 

XML




<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/geeksforgeeks</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">XXX</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property><!-- For criteria query to display , always make it as true -->
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">update </property>
        <!-- We need to specify which hbm file we are going to use here -->
        <mapping resource="geekEmployee.hbm.xml" />
    </session-factory>
</hibernate-configuration>


 
 

 
 

 

Implementation: Let us add a few records to the table so that we can perform criteria operations on it. For adding records, let us do from hibernate itself.

 

 

 

Example 1:

 

 

 

Java




public class GeekEmployeeCriteriaExample {
    private static SessionFactory sessionFactory;
 
    public static void main(String[] args)
    {
        //
        try {
            sessionFactory = new Configuration()
                                 .configure()
                                 .buildSessionFactory();
        }
        catch (Throwable ex) {
            System.err.println(
                "Failed to create sessionFactory object."
                + ex);
            throw new ExceptionInInitializerError(ex);
        }
 
        GeekEmployeeCriteriaExample
            geekEmployeeCriteriaObject
            = new GeekEmployeeCriteriaExample();
 
        /* As a sample let us add some 10 records so that we
         * can see criteria example */
        Integer empID1
            = geekEmployeeCriteriaObject.addEmployee(
                "GeekA", "GeekA", 1000);
        Integer empID2
            = geekEmployeeCriteriaObject.addEmployee(
                "GeekB", "GeekB", 5000);
        Integer empID3
            = geekEmployeeCriteriaObject.addEmployee(
                "GeekC", "GeekC", 10000);
        Integer empID4
            = geekEmployeeCriteriaObject.addEmployee(
                "GeekD", "GeekD", 20000);
        Integer empID5
            = geekEmployeeCriteriaObject.addEmployee(
                "GeekE", "GeekE", 25000);
 
        Integer empID6
            = geekEmployeeCriteriaObject.addEmployee(
                "GeekF", "GeekF", 30000);
        Integer empID7
            = geekEmployeeCriteriaObject.addEmployee(
                "GeekG", "GeekG", 40000);
        Integer empID8
            = geekEmployeeCriteriaObject.addEmployee(
                "GeekH", "GeekH", 50000);
        Integer empID9
            = geekEmployeeCriteriaObject.addEmployee(
                "GeekI", "GeekI", 35000);
        Integer empID10
            = geekEmployeeCriteriaObject.addEmployee(
                "GeekJ", "GeekJ", 85000);
        * /
 
            System.out.println(
                "Listing the data via criteria");
        System.out.println("-----------------------------");
        geekEmployeeCriteriaObject
            .listGeekEmployeesByCriteria();
    }
 
    // This method  List the geekEmployee data whose salary
    // greater than 50000
    public void listGeekEmployeesByCriteria()
    {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
 
        try {
            tx = session.beginTransaction();
            // This will simply return every object that
            // corresponds to the GeekEmployee class.
            Criteria geekEmployeeCriteria
                = session.createCriteria(
                    GeekEmployee.class);
            // As a list we can collect them and can iterate
            List geekEmployeeList
                = geekEmployeeCriteria.list();
            for (Iterator iterator
                 = geekEmployeeList.iterator();
                 iterator.hasNext();) {
                GeekEmployee employee
                    = (GeekEmployee)iterator.next();
                System.out.print("First Name: "
                                 + employee.getFirstName());
                System.out.print("  Last Name: "
                                 + employee.getLastName());
                System.out.println("  Salary: "
                                   + employee.getSalary());
            }
            tx.commit();
        }
        catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        }
        finally {
            session.close();
        }
    }
    /* Method to CREATE an employee in the database */
    public Integer addEmployee(String fname, String lname,
                               int salary)
    {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        Integer employeeID = null;
 
        try {
            tx = session.beginTransaction();
            GeekEmployee employee
                = new GeekEmployee(fname, lname, salary);
            employeeID = (Integer)session.save(employee);
            tx.commit();
        }
        catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        }
        finally {
            session.close();
        }
        return employeeID;
    }
}


 
 

 
 

 

Output: On executing the above code, we can able to see the output in the console as follows:

 

 

 

For all the 10 records, the data is inserted

 

 

 

On console: And also as we have displayed the records via criteria

 

 

 

Displaying data via criteria way

 

 

 

At the same time, we can see the data got inserted in MySQL table also

 

 

 

 

 

 

Using the criteria, we can manipulate the data in different ways.

 

 

 

Filtering the data based on Salary. We need to write the below methods to do that. In SQL, we will filter the day by means of adding the “WHERE” clause. Here in hibernate, we need to use add() method available for the Criteria object and it is helped to add restrictions for a criteria query. It will have all the comparison operations such as >,<,=, between, etc.

 

 

 

Operator Restrictions
> Restrictions.gt
< Restrictions.lt
= Restrictions.eq
between Restrictions.between
Wildcard pattern(like) Restrictions.like

 

 

 

Example 2:

 

 

 

Java




// List out all geekEmployees based on
// the filtering condition with salary
public void listGeekEmployeesBySalary(int salaryRange,
                                      String conditionCheck)
{
 
    Session session = sessionFactory.openSession();
    Transaction tx = null;
 
    // Try block to check for exceptions
    try {
 
        tx = session.beginTransaction();
        // This will simply return every object that
        // corresponds to the GeekEmployee class
        Criteria geekEmployeeCriteria
            = session.createCriteria(GeekEmployee.class);
 
        // Depends upon the condition check, Restrictions
        // are added
        if (conditionCheck != null) {
            if (conditionCheck.equals(">")) {
                geekEmployeeCriteria.add(
                    Restrictions.gt("salary", salaryRange));
            }
            if (conditionCheck.equals("<")) {
                geekEmployeeCriteria.add(
                    Restrictions.lt("salary", salaryRange));
            }
            if (conditionCheck.equals("=")) {
                geekEmployeeCriteria.add(
                    Restrictions.eq("salary", salaryRange));
            }
            if (conditionCheck.equalsIgnoreCase(
                    "between")) {
                geekEmployeeCriteria.add(
                    Restrictions.between("salary", 10000,
                                         30000));
            }
        }
 
        // As a list we can collect them and can iterate
        List geekEmployeeList = geekEmployeeCriteria.list();
 
        for (Iterator iterator
             = geekEmployeeList.iterator();
             iterator.hasNext();) {
            GeekEmployee employee
                = (GeekEmployee)iterator.next();
            System.out.print("First Name: "
                             + employee.getFirstName());
            System.out.print("  Last Name: "
                             + employee.getLastName());
            System.out.println("  Salary: "
                               + employee.getSalary());
        }
 
        tx.commit();
    }
 
    // Catch block to handle the exceptions
    catch (HibernateException e) {
 
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    }
 
    // finally block that will execute for sure
    finally {
 
        // Closing sessions using close() method
        session.close();
    }
}


 
 

 
 

 

We can execute the same by calling in different ways

 

 

 

Java




System.out.println(
    "Listing the geekEmployee data whose salary greater than 50000");
System.out.println(
    "--------------------------------------------------------------------");
// Here in the place of "salary" parameter, 50000 is passed
// and in the place of "conditionCheck" , ">" is passed
geekEmployeeCriteriaObject.listGeekEmployeesBySalary(50000,
                                                     ">");


 
 

 
 

 

Output: On console

 

 

 

salary > 50000

 

 

 

Java




System.out.println("Listing the geekEmployee data whose salary lesser than 50000");
System.out.println("--------------------------------------------------------------------");
geekEmployeeCriteriaObject.listGeekEmployeesBySalary(50000,"<");


 
 

 
 

 

Output: On console

 

 

 

 

 

 

Java




System.out.println("Listing the geekEmployee data whose salary equal to 30000");
System.out.println("----------------------------------------------------------------");
geekEmployeeCriteriaObject.listGeekEmployeesBySalary(30000,"=");


 
 

 
 

 

Output: On console

 

 

 

 

 

 

Java




System.out.println("Listing the geekEmployee data whose salary between 10000 and 30000");
System.out.println("-----------------------------------------------------------------------------");
geekEmployeeCriteriaObject.listGeekEmployeesBySalary(30000,"between");
        


Output: On console

For between

We can combine the queries with the “And”/”Or” condition also.

Example 3:

Java




// Java Program to Illustrate Combining Queries
// With And/Or
 
// Method
// List the geekEmployee data whose firstname like
// certain name and salary > certain value
// We can combine expressions using 'And','Or'
public void listGeekEmployeesByNameAndSalaryCriteria()
{
    Session session = sessionFactory.openSession();
    Transaction tx = null;
 
    // Try block to check for exceptions
    try {
 
        tx = session.beginTransaction();
 
        // This will simply return every object that
        // corresponds to the GeekEmployee class.
        Criteria geekEmployeeCriteria
            = session.createCriteria(GeekEmployee.class);
 
        // Here 2 expectations are there one with salary and
        // second one is name. Both are expected to be
        // present. Let us see how to do that
        Criterion salaryExpectation
            = Restrictions.gt("salary", 40000);
 
        Criterion nameExpectation
            = Restrictions.ilike("firstName", "Geek%");
        // As we are combining 2 conditions and that two
        // logically And, we need to add as Restrictions.and
        // To get records matching with AND conditions we
        // need to give below way
        LogicalExpression logicalAndExpression
            = Restrictions.and(salaryExpectation,
                               nameExpectation);
        geekEmployeeCriteria.add(logicalAndExpression);
 
        // As a list we can collect them and can iterate
        List geekEmployeeList = geekEmployeeCriteria.list();
 
        for (Iterator iterator
             = geekEmployeeList.iterator();
             iterator.hasNext();) {
            GeekEmployee employee
                = (GeekEmployee)iterator.next();
            System.out.print("First Name: "
                             + employee.getFirstName());
            System.out.print("  Last Name: "
                             + employee.getLastName());
            System.out.println("  Salary: "
                               + employee.getSalary());
        }
        tx.commit();
    }
 
    // Catch block to handle exceptions
    catch (HibernateException e) {
 
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    }
 
    // Finally block which will execute for sure
    finally {
 
        // Closing sessions using close() method
        session.close();
    }
}


 
 

 
 

 

Java




System.out.println(
    "Listing the geekEmployee data By Name and Salary With Certain conditions");
System.out.println(
    "-----------------------------------------------------------------------------");
geekEmployeeCriteriaObject
    .listGeekEmployeesByNameAndSalaryCriteria();


 
 

 
 

 

Output: On console

 

 

 

 

 

 

Example 4:

 

 

 

Java




// Java Program to Illustrate Pagination Concept
 
// Method
public void listPaginatedResultsUsingCriteria()
{
 
    Session session = sessionFactory.openSession();
    Transaction tx = null;
 
    // Try block to check for exceptions
    try {
 
        tx = session.beginTransaction();
 
        // This will simply return every object that
        // corresponds to the GeekEmployee class.
        Criteria geekEmployeeCriteria
            = session.createCriteria(GeekEmployee.class);
        // setFirstResult-> It takes an integer and it is
        // represented as the first row in your result set,
        // starting with row 0.
 
        geekEmployeeCriteria.setFirstResult(1);
        // setMaxResults->fixed number maxResults of objects
        // are returned here
        geekEmployeeCriteria.setMaxResults(3);
 
        // As a list we can collect them and can iterate
        List geekEmployeeList = geekEmployeeCriteria.list();
 
        for (Iterator iterator
             = geekEmployeeList.iterator();
             iterator.hasNext();) {
            GeekEmployee employee
                = (GeekEmployee)iterator.next();
            System.out.print("First Name: "
                             + employee.getFirstName());
            System.out.print("  Last Name: "
                             + employee.getLastName());
            System.out.println("  Salary: "
                               + employee.getSalary());
        }
 
        tx.commit();
    }
 
    // Catch block to handle exceptions
    catch (HibernateException e) {
 
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    }
 
    // Finally block which will execute for sure
    finally {
 
        // Closing the connections
        // using close() methods
        session.close();
    }
}


 
 

 
 

 

Java




System.out.println("Displaying Paginated results");
System.out.println("-------------------------------");
geekEmployeeCriteriaObject.listPaginatedResultsUsingCriteria();
        


Output: On console

Example 5:

Java




// Java Program to Sort Records using Criteria
 
// Method
public void listSortedResultsUsingCriteria()
{
 
    Session session = sessionFactory.openSession();
    Transaction tx = null;
 
    // try block to check for exceptions
    try {
        tx = session.beginTransaction();
        // This will simply return every object that
        // corresponds to the GeekEmployee class.
 
        Criteria geekEmployeeCriteria
            = session.createCriteria(GeekEmployee.class);
        geekEmployeeCriteria.add(
            Restrictions.gt("salary", 20000));
 
        // Display the results in descending order
        geekEmployeeCriteria.addOrder(Order.desc("salary"));
 
        // As a list we can collect them and can iterate
        List geekEmployeeList = geekEmployeeCriteria.list();
 
        for (Iterator iterator
             = geekEmployeeList.iterator();
             iterator.hasNext();) {
            GeekEmployee employee
                = (GeekEmployee)iterator.next();
            System.out.print("First Name: "
                             + employee.getFirstName());
            System.out.print("  Last Name: "
                             + employee.getLastName());
            System.out.println("  Salary: "
                               + employee.getSalary());
        }
 
        tx.commit();
    }
 
    // Catch block to handle exceptions
    catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
 
        // Display exceptions with line numbers
        // using printStackTrace() method
        e.printStackTrace();
    }
 
    // Finally block
    // It will execute for sure
    finally {
        session.close();
    }
}
 
System.out.println("Displaying sorted results");
System.out.println("---------------------------");
geekEmployeeCriteriaObject.listSortedResultsUsingCriteria();


 
 

 
 

 

Output: On console

 

 

 

descending order listing of data

 

 

 

Aggregations are a very useful part of report preparations. In Hibernate, it can be possible by means of Projections

 

 

 

Aggregation Hibernate way with Projections
Get RowCount Projections.rowCount()
Get sum of salary Projections.sum(“salary”)
Get average of salary Projections.avg(“salary”)
Get maximum salary Projections.max(“salary”)
Get minimum salary Projections.min(“salary”)

 

 

 

Example 6:

 

 

 

Java




// Java Program to Illustrate Aggregations
 
// Method
// to get total count, sum(salary),
// max(salary),min(salary),avg(salary)
public void displayAggregatedValuesUsingCriteria()
{
 
    Session session = sessionFactory.openSession();
    Transaction tx = null;
 
    // Try block to check for exceptions
    try {
 
        tx = session.beginTransaction();
 
        // This will simply return every object that
        // corresponds to the GeekEmployee class.
        Criteria geekEmployeeCriteria
            = session.createCriteria(GeekEmployee.class);
 
        // Get total number of records by using rowcount
        geekEmployeeCriteria.setProjection(
            Projections.rowCount());
        List employeeRowCount = geekEmployeeCriteria.list();
 
        System.out.println("Total row Count: "
                           + employeeRowCount.get(0));
 
        // Getting sum(salary)
        geekEmployeeCriteria.setProjection(
            Projections.sum("salary"));
        List totalSalary = geekEmployeeCriteria.list();
 
        System.out.println("Total Salary of GeekEmployees: "
                           + totalSalary.get(0));
 
        // Getting average(salary)
        geekEmployeeCriteria.setProjection(
            Projections.avg("salary"));
        List averageSalary = geekEmployeeCriteria.list();
        System.out.println(
            "Average Salary of GeekEmployees: "
            + averageSalary.get(0));
 
        // Getting max(salary)
        geekEmployeeCriteria.setProjection(
            Projections.max("salary"));
        List maxSalary = geekEmployeeCriteria.list();
        System.out.println(
            "Maximum Salary among GeekEmployees: "
            + maxSalary.get(0));
 
        // Getting min(salary)
        geekEmployeeCriteria.setProjection(
            Projections.min("salary"));
        List minSalary = geekEmployeeCriteria.list();
        System.out.println(
            "Minimum salary among GeekEmployees: "
            + minSalary.get(0));
 
        tx.commit();
    }
 
    // Catch block to handle exceptions
    catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
 
        // Printing exceptions with line number
        // using printStackTrace() method
        e.printStackTrace();
    }
 
    // Finally block
    finally {
 
        // Closing connections
        session.close();
    }
}
 
// Display message only
System.out.println("Displaying Aggregated results");
 
// Display command for better readability of output
System.out.println("--------------------------------");
 
geekEmployeeCriteriaObject
    .displayAggregatedValuesUsingCriteria();


 
 

 
 

 

Output: On console

 

 

 

 

 

 

Video explanation of the concepts explained for criteria queries are as follows:

 

 

 

Conclusion: As explained in the above examples, we can perform different criteria and they will help to filter out, paginate and sort the results as per our needs. Hence they are much useful in programming.

 

 

 



Previous Article
Next Article

Similar Reads

Hibernate - Create Hibernate Configuration File with the Help of Plugin
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is a java framework that is used to develop persisten
3 min read
JPA - Criteria SELECT Clause
In Java, JPA is defined as the Java Persistence API and the Criteria API provides a systematic way to create queries dynamically. It provides more flexibility and type safety compared to JPQL (Java Persistence Query Language). Criteria SELECT ClauseThe Criteria API in JPA allows developers to construct queries using various Java objects that repres
5 min read
Hibernate - Annotations
Annotation in JAVA is used to represent supplemental information. As you have seen @override, @inherited, etc are an example of annotations in general Java language. For deep dive please refer to Annotations in Java. In this article, we will discuss annotations referred to hibernate. So, the motive of using a hibernate is to skip the SQL part and f
7 min read
Introduction to Hibernate Framework
Prerequisite : JDBC Need of Hibernate Framework Hibernate is used to overcome the limitations of JDBC like: JDBC code is dependent upon the Database software being used i.e. our persistence logic is dependent, because of using JDBC. Here we are inserting a record into Employee table but our query is Database software-dependent i.e. Here we are usin
4 min read
Hibernate - Cache Eviction with Example
Caching in Hibernate means storing and reusing frequently used data to speed up your application. There are two kinds of caching: Session-level and SessionFactory-level. Level 1 cache is a cache that stores objects that have been queried and persist to the current session. This cache helps to reduce the number of database round trips by storing obj
9 min read
Hibernate - Bag Mapping
For a multi-national company, usually, selections are happened based on technical questions/aptitude questions. If we refer to a question, each will have a set of a minimum of 4 options i.e each question will have N solutions. So we can represent that by means of "HAS A" relationship i.e. 1 question has 4 solutions. Via Bag Mapping, in Hibernate, w
4 min read
Difference between JDBC and Hibernate in Java
Java is one of the most powerful and popular server-side languages in the current scenario. One of the main features of a server-side language is the ability to communicate with the databases. In this article, let's understand the difference between two ways of connecting to the database (i.e.) JDBC and Hibernate. Before getting into the difference
2 min read
Hibernate Example using XML in Eclipse
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc. In this article, let us see a Hibernate Example using XM
6 min read
Hibernate Lifecycle
Here we will learn about Hibernate Lifecycle or in other words, we can say that we will learn about the lifecycle of the mapped instances of the entity/object classes in hibernate. In Hibernate, we can either create a new object of an entity and store it into the database, or we can fetch the existing data of an entity from the database. These enti
4 min read
Java - JPA vs Hibernate
JPA stands for Java Persistence API (Application Programming Interface). It was initially released on 11 May 2006. It is a Java specification that gives some functionality and standard to ORM tools. It is used to examine, control, and persist data between Java objects and relational databases. It is observed as a standard technique for Object Relat
4 min read
Spring Boot - Integrating Hibernate and JPA
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Hibernate - Difference Between ORM and JDBC
Hibernate is a framework that is used to develop persistence logic that is independent of Database software. In JDBC to develop persistence logic, we deal with primitive types. Whereas Hibernate framework we use Objects to develop persistence logic that is independent of database software. ORM (Object-Relational Mapping) ORM, an abbreviation for Ob
4 min read
Hibernate - Generator Classes
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. In JDBC to develop persistence logic, we deal with primitive types. Whereas in Hibernate framework we use Objects to develop persistence logic that is independent of
5 min read
Hibernate - Create POJO Classes
POJO stands for Plain Old Java Object. In simple terms, we use POJO to make a programming model for declaring object entities. The classes are simple to use and do not have any restrictions as compared to Java Beans. To read about POJO classes and Java Bean refer to the following article - POJO classes and Java Bean POJO is handier as its best in r
3 min read
Hibernate - One-to-One Mapping
Prerequisite: Basic knowledge of hibernate framework, Knowledge about databases, Java Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to
15 min read
Hibernate - SQL Dialects
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. An ORM(Object-relational mapping) framework simplifies data creation, data manipulation, and data access. It is a programming technique that maps the object to the d
3 min read
Hibernate - Web Application
A web application with hibernate is easier. A JSP page is the best way to get user inputs. Those inputs are passed to the servlet and finally, it is inserted into the database by using hibernate. Here JSP page is used for the presentation logic. Servlet class is meant for the controller layer. DAO class is meant for database access codes. Tools and
9 min read
Hibernate - Table Per Concrete Class using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time application, POJO classes of Hibernate are design
5 min read
Hibernate - Table Per Subclass using Annotation
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. An ORM(Object-relational mapping) framework simplifies data creation, data manipulation, and data access. It is a programming technique that maps the object to the d
6 min read
Hibernate - Table Per Hierarchy using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time application, POJO classes of Hibernate are design
6 min read
Hibernate - Table Per Subclass Example using XML File
In Table Per Subclass, subclass tables are mapped to the Parent class table by primary key and foreign key relationship. In a Table per Subclass strategy : For each class of hierarchy there exist a separate table in the database.While creating the database tables foreign key relationship is required between the parent table and the child table.To p
5 min read
Hibernate - Table Per Hierarchy using Annotation
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, it does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is an open-source, non-invasive, lightweight java ORM(Object
8 min read
Hibernate - Types of Mapping
Hibernate is a Java framework that simplifies the development of Java applications to interact with the database. It is an open-source, lightweight, ORM (Object Relational Mapping) tool. Hibernate implements the specifications of JPA (Java Persistence API) for data persistence. There are different relations that we maintain to establish a link betw
2 min read
Hibernate - Many-to-Many Mapping
In RDBMS, we can see a very common usage of parent-child relationships. It can be achieved in Hibernate via One-to-many relationshipMany-to-one relationshipOne-to-one relationshipMany-to-many relationship Here we will be discussing how to perform Hibernate - Many-to-Many mappings. Below are the example tables to demonstrate Many-to-Many mappings as
12 min read
Hibernate - Interceptors
Interceptors are used in conjunction with Java EE managed classes to allow developers to invoke interceptor methods on an associated target class, in conjunction with method invocations or lifecycle events. Common uses of interceptors are logging, auditing, and profiling. The Interceptors 1.1 specification is part of the final release of JSR 318, E
6 min read
Hibernate - Table Per Concrete Class Using Annotation
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, it does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is an open-source, non-invasive, lightweight java ORM(Object
7 min read
Hibernate - Logging By Log4j Using Properties File
Apache log4j is a java-based logging utility. Apache log4j role is to log information to help applications run smoothly, determine what’s happening, and debug processes when errors occur. log4j may logs login attempts (username, password), submission form, and HTTP headers (user-agent, x-forwarded-host, etc.) into the log file or database. Apache l
2 min read
Hibernate - Many-to-One Mapping
Hibernate is an open-source, ORM(Object Relational Mapping) framework that provides CRUD operations in the form of objects. It is a non-invasive framework. It can be used to develop DataAcessLayer for all java projects. It is not server-dependent. It means hibernate code runs without a server and with a server also. It is a top layer of JDBC, JTA,
5 min read
Hibernate - Logging by Log4j using xml File
The process of Hibernate Logging by Log4j using an XML file deals with the ability of the computer programmer to write the log details of the file he has created by executing it permanently. The most important tools in Java language like the Log4j and Log back frameworks. These frameworks in Java language help the programmer to install and initiate
5 min read
Hibernate - Native SQL
Hibernate by means of a Native SQL facility, can directly interact with the database like MySQL, Oracle, etc., and all the database-specific queries can be executed via this facility. This feature is much useful if the application is an old application and running for a long time. All of a sudden we cannot bring back new changes but instead with Na
8 min read
three90RightbarBannerImg