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.
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)");
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