How do I retrieve object from database in Hibernate?

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 org.hibernate.Query;
import org.hibernate.Session;
import org.kodejava.example.hibernate.model.Label;

import java.util.List;

public class LabelManager {
    public Label getLabel(Integer 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;
    }

    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;

public class SaveLoadDemo {
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 and created date information.

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA. Support me by donating >> here <<.