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

29,539

Solution 1

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

Solution 2

The problem you have with Hibernate you can't get the persistence instance by some property value, only can do it by id. If you want to find an instance by userName try this

public static final String USER_NAME = "userName";

private List<User> findByProperty(String propertyName, Object value) {
    log.debug("finding User instance with property: " + propertyName    + ", value: " + value);
    try {
        String queryString = "from User as model where model." + propertyName   + "= ?";
        Query queryObject = getSession().createQuery(queryString);
        queryObject.setParameter(0, value);
        return queryObject.list();
    } catch (RuntimeException re) {
        log.error("find by property name failed", re);
        throw re;
    }
}

public List<User> findByUserName(Object userName) {
    return findByProperty(USER_NAME, userName);
}

@Override
public void deleteUsers(String userName) {
  try {
    List<User> list = findByUserName(userName);
    for (User user: list)
      getSession().delete(user);
    log.debug("delete successful");
  } catch (RuntimeException re) {
    log.error("delete failed", re);
    throw re;
  }
}  

that will delete all users with the given name, to delete the unique user make sure the user_name field has unique constraint. It could be done via annotation on the table

@Table(name = "user", uniqueConstraints = {
        @UniqueConstraint(columnNames = "user_name")
})

Solution 3

You have to write a query to get the user by userName.

e.g.

String qStr = "from User user where user.userName = :userName";
//then run the query to get the user
Query q = session.createQuery(qStr);
q.setParameter("userName", userName);
List<User> users = (List<User>) q.list();
//if the list is not empty, then users.get(0) will give you the object
Share:
29,539
Aadam
Author by

Aadam

Updated on July 09, 2022

Comments

  • Aadam
    Aadam almost 2 years

    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.