Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using Struts2+Hibernate and have been understanding by example on net. In one of the examples here struts2+hibernate example

What 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 text field given there and that should be able to delete 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.

like image 421
Aadam Avatar asked Dec 15 '22 12:12

Aadam


1 Answers

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)");
like image 86
Marek Piechut Avatar answered Apr 27 '23 00:04

Marek Piechut