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?
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") .
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With