How do I delete persistent object in Hibernate?

Continuing the previous example How do I get object from database in Hibernate?, we now add the delete function in our LabelManager class.

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 void deleteLabel(Integer id) {
        //
        // Load the object to be deleted
        //
        Label label = getLabel(id);

        //
        // We get the current session and delete the Label object from database.
        //
        Session session = SessionFactoryHelper.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        session.delete(label);
        session.getTransaction().commit();
    }
}
package org.kodejava.example.hibernate.app;

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

import java.util.Date;

public class DeleteDemo {
    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.
        //
        Label label = new Label();
        label.setName("Sony Music");
        label.setCreated(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);

        manager.deleteLabel(label.getId());
    }
}

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 <<.

Leave a Reply