Reputation: 1123
I tried to delete multiple rows from database using Hibernate. Its successfully done.
When I refresh the .jsp page, the deleted items will shown again.
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.
Ideas?
Upvotes: 0
Views: 2442
Reputation: 1657
the user you fetch in getUserByID is queried in its own session which is closed and the user returned is detached. 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.
Upvotes: 3