通过任何列值hibernate删除记录

时间:2013-03-20 20:13:46

标签: java hibernate java-ee struts2

我是hibernate的新手,我正在学习struts2 + hibernate并且已经通过网络上的例子进行了解。在其中一个示例中strts2+hibernate example

我可以看到和做的是,通过他们的id删除用户,正如我们在那里看到的,列表中的每个用户都提供了删除链接,而session.delete()现在按id删除了记录我希望用户在那里给出的文本字段中输入名称,并且应该能够按名称删除。到目前为止,我已经尝试过这样的

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();
    } 
}

我希望hibernate可以通过提供的任何字段值删除行。以上什么都不做。

此致

4 个答案:

答案 0 :(得分:5)

为什么不简单地使用JPQL删除查询?这不需要hibernate从DB恢复任何对象到简单删除它。以下是如何在不首先从DB加载的情况下按名称删除用户的方法:

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

答案 1 :(得分:4)

你对Hibernate的问题是你无法通过某个属性值获取持久性实例,只能通过id来实现。如果您想通过userName查找实例,请尝试使用此

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;
  }
}  

将删除具有给定名称的所有用户,以删除唯一用户,确保user_name字段具有唯一约束。它可以通过表格上的注释来完成

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

答案 2 :(得分:1)

您必须编写一个查询,以便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

答案 3 :(得分:0)

public void deleteUser(Integer id)
{
    session = sessionfactory.openSession();
    tx = session.beginTransaction();
    try
    {           
        Query q=session.createQuery("delete from UserValidateLogin where userId=:userId");  
        q.setParameter("userId",id);  

        q.executeUpdate();    
        tx.commit();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        session.close();
    }

}