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 =

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

        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()

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.setCreated(new Date());

        // Call the LabelManager saveLabel method.

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

Maven Dependencies

    <!-- -->
    <!-- -->

Maven Central Maven Central

Leave a Reply

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