javahibernatestruts2crud

How to delete a record by any column value using Hibernate with Struts 2


I am using Struts 2 + Hibernate, and I have been learning the examples. In one of the examples here: struts2+hibernate example

I can see and do is, to delete an user by their id, as we can see there, a delete link is provided to each user in the list, and the session.delete() deletes the record by id.

Now, I want the user to enter the name in the textfield, given there, so that I should be able to delete a record by the name. So far I have tried like this

ActionMethod:

public String delete()
{
    //HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get( ServletActionContext.HTTP_REQUEST);
    //userDAO.delUser(Long.parseLong( request.getParameter("id")));
            userDAO.delUser(user.getName());
    return SUCCESS;
}

DAOImpl:

@Override
public void delUser(String userName) {
    try {
        User user = (User) session.get(User.class, userName);
        session.delete(user);
    } catch (Exception e) {
        transaction.rollback();
        e.printStackTrace();
    } 
}

I hope, there is a way that Hibernate can delete a row by any field value provided. The above does nothing.


Solution

  • Why not simply use JPQL delete query? This will not require hibernate to restore any object from DB to simple delete it. Here's how you can delete user by name without loading it from DB first:

        Query query = em.createQuery("delete from User where name=:name");
        query.setParameter("name", "Zigi");
        int deleted = query.executeUpdate();
        System.out.println("Deleted: " + deleted + " user(s)");