How do I retrieve a list of Hibernate’s persistent objects?

In this example we add the function to read a list of records in our LabelService class. This function will read all Label persistent object from database. You can see the other functions such as saveLabel, getLabel and deleteLabel in the related example section of this example.

package org.kodejava.hibernate.service;

import org.hibernate.Session;
import org.kodejava.hibernate.SessionFactoryHelper;
import org.kodejava.hibernate.model.Label;

import java.util.List;

public class LabelService {
    public List<Label> getLabels() {
        Session session =
                SessionFactoryHelper.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        // We read labels record from database using a simple Hibernate
        // query, Hibernate Query Language (HQL).
        List<Label> labels = session.createQuery("from Label", Label.class)
                .list();
        session.getTransaction().commit();

        return labels;
    }

    public void saveLabel(Label label) {
        // To save an object we first get a session by calling 
        // getCurrentSession() method from the SessionFactoryHelper class. 
        // Next we create a new transaction, save the Label object and 
        // commit it to database,
        Session session = SessionFactoryHelper.getSessionFactory()
                .getCurrentSession();

        session.beginTransaction();
        session.save(label);
        session.getTransaction().commit();
    }
}
package org.kodejava.hibernate;

import org.kodejava.hibernate.model.Label;
import org.kodejava.hibernate.service.LabelService;

import java.util.Date;
import java.util.List;

public class ListDemo {
    public static void main(String[] args) {
        LabelService service = new LabelService();

        // Creates a Label object we are going to store in the database.
        // We set the name, modified by and modified date information.
        Label newLabel = new Label();
        newLabel.setName("PolyGram");
        newLabel.setCreated(new Date());

        // Call the LabelManager saveLabel method.
        service.saveLabel(newLabel);

        List<Label> labels = service.getLabels();
        for (Label label : labels) {
            System.out.println("Label = " + label);
        }
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I delete persistent object in Hibernate?

Continuing the previous example How do I get object from database in Hibernate?, we now add the delete function in our LabelService class.

package org.kodejava.hibernate.service;

import org.hibernate.Session;
import org.kodejava.hibernate.SessionFactoryHelper;
import org.kodejava.hibernate.model.Label;

public class LabelService {
    public Label getLabel(Long id) {
        Session session =
                SessionFactoryHelper.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        // We get back Label object from database by calling the Session
        // object get() method and passing the object type and the object
        // id to be read.
        Label label = session.get(Label.class, id);
        session.getTransaction().commit();

        return label;
    }

    public void deleteLabel(Long id) {
        // Load the object to be deleted
        Label label = getLabel(id);

        // We get the current session and delete the Label object from 
        // database.
        Session session =
                SessionFactoryHelper.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        session.delete(label);
        session.getTransaction().commit();
    }
}
package org.kodejava.hibernate;

import org.kodejava.hibernate.model.Label;
import org.kodejava.hibernate.service.LabelService;

import java.util.Date;

public class DeleteDemo {
    public static void main(String[] args) {
        LabelService service = new LabelService();

        // Creates a Label object we are going to store in the database.
        // We set the name and created date information.
        Label label = new Label();
        label.setName("Sony Music");
        label.setCreated(new Date());

        // Call the LabelManager saveLabel method.
        service.saveLabel(label);

        // Read the object back from database.
        label = service.getLabel(label.getId());
        System.out.println("Label = " + label);

        service.deleteLabel(label.getId());
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I retrieve object from database in Hibernate?

In the How do I store object in Hibernate? example you’ll see how tho store objects into database. In this example we’ll extend the LabelService class and add the capability to get or query object from database.

package org.kodejava.hibernate.service;

import org.hibernate.Session;
import org.kodejava.hibernate.SessionFactoryHelper;
import org.kodejava.hibernate.model.Label;

public class LabelService {
    public Label getLabel(Long id) {
        Session session =
                SessionFactoryHelper.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        // We get back Label object from database by calling the Session
        // object get() method and passing the object type and the object
        // id to be read.
        Label label = session.get(Label.class, id);
        session.getTransaction().commit();

        return label;
    }
}
package org.kodejava.hibernate;

import org.kodejava.hibernate.model.Label;
import org.kodejava.hibernate.service.LabelService;

public class LoadDemo {
    public static void main(String[] args) {
        // Create an instance of LabelService.
        LabelService service = new LabelService();

        // We call the getLabel() method and pass the label id to load it
        // from the database and print out the label string.
        Label label = service.getLabel(1L);
        System.out.println("label = " + label);
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I store object in Hibernate?

This example shows you how to store or save Hibernate object to database. The basic steps in creating application in Hibernate will be:

  • Creates the POJO
  • Create hibernate mapping file
  • Register the mapping file in hibernate configuration
  • Create a simple service class to store the object

In this example we’ll create a class called Label, this class is about a record label company. This class has the id, name, created and modified properties. Their types in order are Long, String, java.util.Date and java.util.Date.

Hibernate is an Object-Relational-Mapping (ORM) technology, which basically means how a Java object is mapped to a relational database model/table. Because of this, it needs a mapping file to map the object properties to table columns. The mapping file usually named in the format of Label.hbm.xml, the class name with hbm.xml suffix. And for Hibernate application recognize the object, the mapping file should be registered in hibernate configuration file (hibernate.cfg.xml).

We have a brief introduction about Hibernate class and configuration structure. Let’s jump to the working example. First we create the mapping file, and then we create the classes.

Create Label.hbm.xml mapping file.

In a maven project this file must be placed under the resources directory. In this example we place it in the org/kodejava/hibernate/mapping directory.

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="org.kodejava.hibernate.model.Label" table="labels">
        <id name="id" column="id">
            <generator class="identity" />
        </id>
        <property name="name" not-null="true" />
        <property name="created" column="created" type="timestamp" />
        <property name="modified" column="modified" type="timestamp" />
    </class>
</hibernate-mapping>

Create Label.java class.

package org.kodejava.hibernate.model;

import java.util.Date;

public class Label {
    private Long id;
    private String name;
    private Date created;
    private Date modified;

    // Getters & Setters 

    @Override
    public String toString() {
        return "Label{" +
            "id=" + id +
            ", name='" + name + '\'' +
            ", created=" + created +
            ", modified=" + modified +
            '}';
    }
}

Create the LabelService.java class.

This class will handle the CRUD operation for our Label entity. In this example we start with the create/insert operation.

package org.kodejava.hibernate.service;

import org.hibernate.Session;
import org.kodejava.hibernate.SessionFactoryHelper;
import org.kodejava.hibernate.model.Label;

public class LabelService {
    public void saveLabel(Label label) {
        // To save an object we first get a session by calling 
        // getCurrentSession() method from the SessionFactoryHelper class. 
        // Next we create a new transaction, save the Label object and 
        // commit it to database,
        Session session = SessionFactoryHelper.getSessionFactory()
                .getCurrentSession();

        session.beginTransaction();
        session.save(label);
        session.getTransaction().commit();
    }
}

Create the InsertDemo.java class.

package org.kodejava.hibernate;

import org.kodejava.hibernate.model.Label;
import org.kodejava.hibernate.service.LabelService;

import java.util.Date;

public class InsertDemo {
    public static void main(String[] args) {
        LabelService service = new LabelService();

        // Creates a Label object we are going to be stored in the database.
        // We set the name, modified by and modified date information.
        Label label = new Label();
        label.setName("Sony Music");
        label.setCreated(new Date());

        // Call the LabelManager saveLabel method.
        service.saveLabel(label);
    }
}

Register mapping file in hibernate.cfg.xml.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>

        <!-- Mapping to hibernate mapping files -->
        <mapping resource="org/kodejava/hibernate/mapping/Label.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

We have the code and the mapping file done. To register the mapping file in hibernate configuration file you can see the How do I create Hibernate’s SessionFactory? example. The example also tells you how to create the SessionFactoryHelper class to obtain Hibernate’s SessionFactory.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I create Hibernate’s SessionFactory?

When creating an application the use Hibernate to manage our application persistence object we’ll need a SessionFactory. This factory creates or open a session to talk to a database.

To create a SessionFactory we can define the configuration in hibernate.properties, hibernate.cfg.xml or create it programmatically. In this example we’ll use the hibernate.cfg.xml configuration file, which is mostly use when creating Hibernate application.

Below is our session configuration files.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- JDBC connection settings -->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/musicdb</property>
        <property name="connection.username">root</property>
        <property name="connection.password" />

        <!-- JDBC connection pool, use Hibernate internal connection pool -->
        <property name="connection.pool_size">5</property>

        <!-- Defines the SQL dialect used in Hibernate's application -->
        <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCachingRegionFactory</property>

        <!-- Display and format all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

        <!-- Mapping to hibernate mapping files -->
        <mapping resource="org/kodejava/hibernate/mapping/Label.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Now we have the configuration file done, let’s create a helper class that will configure and build the SessionFactory object. This helper will be used in other Hibernate example in this site.

package org.kodejava.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class SessionFactoryHelper {
    private static final SessionFactory sessionFactory;

    static {
        try {
            // Build a SessionFactory object from session-factory config
            // defined in the hibernate.cfg.xml file. In this file we
            // register the JDBC connection information, connection pool,
            // hibernate dialect that we used and the mapping to our
            // hbm.xml file for each pojo (plain old java object).
            Configuration config = new Configuration();
            sessionFactory = config.configure().buildSessionFactory();
        } catch (Throwable e) {
            System.err.println("Error in creating SessionFactory object."
                    + e.getMessage());
            throw new ExceptionInInitializerError(e);
        }
    }

    public static void main(String[] args) {
        Session session = SessionFactoryHelper.getSessionFactory()
                .getCurrentSession();
        System.out.println("session = " + session);
    }

    /**
     * A static method for other application to get SessionFactory object
     * initialized in this helper class.
     */
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

Maven Central Maven Central