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

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.