Delete and Edit query in Hibernate Example

Delete functionality in hibernate

If you use HibernateDAOTemplate in your application you can refer the following code for the delete function this is a working example.

I am extending the HibernateDAOTemplate  so I will get the session object directly.
public class PasswordDaoImpl  extends HibernateDaoSupport implements PasswordDao

In this method the row id is passing as input. By creating a session object invoking the createQuery() method.

public int delPassword(int id) {
   Session session=getSession();
   String hql = "delete from Password where id= :id";
   session.createQuery(hql).setInteger("id", new Integer(id)).executeUpdate();
   return 0;

  • Password is the domain class name.
  • Getting the session object in the initial of class.
 Edit Query using hibernate Example

 public void editPassword(Password pw) {
    Query query = getSession().createQuery("update Password  set source=:src," +
    "userName=:user,password=:pw,remarks=:remarks where id=:id");
    query.setParameter("src", pw.getSource());
    query.setParameter("user", pw.getUserName());
    query.setParameter("pw", pw.getPassword());
    query.setParameter("remarks", pw.getRemarks());
    query.setParameter("id", pw.getId());
    query.executeUpdate();"editing password for the source: " + pw.getSource());