java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.example.hibernate.app;

import java.util.Date;

import java.util.List;

import org.hibernate.Session;

public class LabelManager {

    private 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;
    }
    
    private 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
         * transcation, save the Label object and commit it to database,
         */
        Session session = SessionFactoryHelper.getSessionFactory().getCurrentSession();
        
        session.beginTransaction();        
        session.save(label);        
        session.getTransaction().commit();
    }

    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.setModifiedBy("admin");
        label.setModifiedDate(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);
        }
    }
}