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>
    <!-- https://search.maven.org/remotecontent?filepath=org/hibernate/hibernate-core/5.5.7.Final/hibernate-core-5.5.7.Final.jar -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.5.7.Final</version>
    </dependency>
    <!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.26/mysql-connector-java-8.0.26.jar -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.26</version>
    </dependency>
</dependencies>

Maven Central Maven Central