Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Spring HibernateTemplate. How to delete by Id?

For work with database, my class extends HibernateDaoSupport class and inside the methods I'm using Spring HibernateTemplate.

So, for delete a row in database I use this method:

public void delete(MyObject obj) {
    getHibernateTemplate().delete(obj);
}

all ok!

But, at this moment I'm trying to implement a method that can delete a row based on id:

public void delete(final long id) {
    // some code here
}

And I can't find some HibernateTemplate method like this:
getHibernateTemplate().remove(id)

What is a good solution for me in this case?

like image 632
user471011 Avatar asked Jan 23 '12 11:01

user471011


People also ask

How to delete in Hibernate query?

Deletion Using a JPQL Statement Hibernate supports DML-style delete operations: Foo foo = new Foo("foo"); entityManager. persist(foo); flushAndClear(); entityManager. createQuery("delete from Foo where id = :id") .

How to delete data from table using Hibernate?

In Hibernate, an entity can be removed from a database by calling the Session#delete() or Session#remove() . Using these methods, we can remove a transient or persistent object from datastore.

What is remove method in Hibernate?

In Hibernate, an entity can be removed from a database by calling the Session. delete() or Session. remove(). Using these methods, we can remove a transient or persistent object from datastore.


2 Answers

There is a simple solution by creating an object and setting only the ID:

Product product = new Product();
product.setId(37);
session.delete(product);

The drawback of this simple solution is that it doesn’t remove the associated instances.
If you have some attribute (another entity related) of the product to be deleted, you will need to load the product before.

 Serializable id = new Long(17); 
 Object persistentInstance = session.load(Product.class, id); 
 if (persistentInstance != null) 
 {
   session.delete(persistentInstance); 
 }

This will issue (if you have an attribute table in cascade) a delete on the children attributes.

like image 190
maborg Avatar answered Oct 21 '22 15:10

maborg


delete using particular id,

public void delete(long id)
{
    Session session ;
    MyObject myObject ;

    session = sessionFactory.getCurrentSession();
    myObject = (MyObject)session.load(MyObject.class,id);
    session.delete(myObject);

    //This makes the pending delete to be done
    session.flush() ;

}

Also consider encapuslate this methods in try/catch/finally and log the error as needed

like image 26
Kushan Avatar answered Oct 21 '22 16:10

Kushan