user471011 user471011 - 2 months ago 11
Java Question

HibernateTemplate. How delete by Id?

For work with database my class extends

HibernateDaoSupport
class and inside class methods I use
HibernateTemplate
.

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

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


all ok!

But, at this moment I try implement method, that can delete row based on Id:

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


And I cant find HibernateTemplate method some like this:
getHibernateTemplate().remove(id)
.

How solution for me in this case?

Answer

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