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 LabelManager 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.example.hibernate.app;

import org.hibernate.Query;
import org.hibernate.Session;
import org.kodejava.example.hibernate.model.Label;

import java.util.List;

public class LabelManager {

    public List getLabels() {
        Session session = SessionFactoryHelper.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        //
        // We read labels record from database using a simple Hibernate query,
        // the Hibernate Query Language (HQL).
        //
        List labels = session.createQuery("from Label").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.example.hibernate.app;

import org.kodejava.example.hibernate.model.Label;

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

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

        //
        // Creates a Label object we are going to 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.
        //
        manager.saveLabel(label);

        List labels = manager.getLabels();
        for (int i = 0; i < labels.size(); i++) {
            label = (Label) labels.get(i);
            System.out.println("Label = " + label);
        }
    }
}

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply