How do I retrieve object from database in Hibernate?

Category: org.hibernate, viewed: 11941 time(s).

In the How do I store object in Hibernate? example you'll see how tho store objects into database. In this example we'll extends the LabelManager class and add the capability to get or query object from database.

package org.kodejava.example.hibernate.app;

import java.util.Date;

import org.hibernate.Session;

public class LabelManager {
    private 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 = (Label) session.get(Label.class, id);
        session.getTransaction().commit();
        
        return label;
    }

    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);
        
        /*
         * Read the object back from database.
         */
        label = manager.getLabel(label.getId());
        System.out.println("Label = " + label);
    }    
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats