简体   繁体   English

Hibernate:如何在Hibernate中删除多行?

[英]Hibernate:How to delete multiple rows in Hibernate?

I tried to delete multiple rows from database using Hibernate . 我试图使用Hibernate从数据库中删除多行。 Its successfully done. 其成功完成。

When I refresh the .jsp page, the deleted items will shown again. 当我刷新.jsp页面时,删除的项目将再次显示。

Here's my code: 这是我的代码:

public int deleteUserById(String id[])
{
  SessionFactory sf = HibernateUtil.getSessionFactory();

  int flag = 0;

  User user;
  try
  {

    for (int i = 0; i < id.length; i++)
    {
      Session session = sf.openSession();
      session.beginTransaction();

      Long Id = Long.parseLong(id[i]);

      user = new UserRepository().getUserByID(Id);

      session.delete(user);
      session.getTransaction().commit();
      session.close();

    }
    flag = 1;
  }
  catch (Exception e)
  {
    System.out.println("Error in deleteUserById=" + e);
  }
  return flag;
}

Other Method: 其他方法:

public User getUserByID(Long Id)
{
  SessionFactory sf = HibernateUtil.getSessionFactory();
  Session session = sf.openSession();
  session.beginTransaction();

  User user = null;

  try
  {
    user = (User) session.createQuery("from User where Id='" + Id + "'").list().get(0);
  }
  catch (Exception e)
  {
    System.out.println("Error in getUserByID=" + e);
  }

  session.close();
  return user;
}

Getting User method: 获取用户方法:

public ArrayList<User> getAllUser()
{
  ArrayList<User> list_user = new ArrayList<User>();

  SessionFactory sf = HibernateUtil.getSessionFactory();

  Session session = sf.openSession();
  session.beginTransaction();

  try
  {
    list_user = (ArrayList<User>) session.createQuery("from User").list();
  }
  catch (Exception e)
  {
    System.out.println("Error in getAllUser=" + e);
  }

  session.close();
  return list_user;
}

I had used session.clear() but this doesn't solve the problem. 我使用过session.clear()但这不能解决问题。

Ideas? 有想法吗?

the user you fetch in getUserByID is queried in its own session which is closed and the user returned is detached. 在您自己的会话中查询您在getUserByID中获取的用户,该会话已关闭,并且返回的用户已分离。 You should have one session per Request but you have nested sessions. 每个请求应该有一个会话,但是您有嵌套的会话。

Try opening a session and a transaction at the beginning of the Request and commit the transaction at the end and eventually close the session. 尝试在请求的开头打开会话和事务,并在结尾处提交事务,最后关闭会话。

if you really want to use a session of it's own for querying, then you have to merge the detached result : 如果您真的想使用它自己的会话进行查询,则必须合并分离的结果:

   user = session.merge(new UserRepository().getUserByID(Id));

Note : You are using many sessions and transactions in the for-loop in "deleteUserById" .... this is going to be rather resource consuming ... better open the session and transaction around that loop. 注意:您正在for循环中的“ deleteUserById”中使用许多会话和事务……这将是相当耗资源的……最好围绕该循环打开会话和事务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM