2015-09-27 75 views
0

我想从我的servlet更新我的数据库中的一个对象。然而,它成功运行没有任何错误,但不会删除。休眠,并发故障

我HibernateUtil的样子:

public class HibernateUtil { 

    private static SessionFactory sessionFactory; 
    private static final String HIBER = "hibernate.cfg.xml"; 

    public HibernateUtil() { 
     try { 
      sessionFactory = new Configuration().addResource(HIBER).configure() 
        .buildSessionFactory(); 
     } catch (HibernateException ex) { 
      System.out.println(ex); 
     } 
    } 

    public SessionFactory getSessionFactory() { 
     return sessionFactory; 
    } 

    public void closeSessionFactory() { 
     sessionFactory.close(); 
    } 
} 

和我上面的实例化类时,servlet初始化。

@Override 
    public void init() { 

     hiber = new HibernateUtil(); 
     System.out.println("Servlet Initialized"); 
    } 

我之前使用的openSession,并阅读,这是更好地使用的getCurrentSession为Web应用程序,现在我正在努力做到这一点了。

String add = request.getParameter("houseId"); 
      hiber.getSessionFactory().getCurrentSession(); 
      Transaction tx = session1.beginTransaction(); 

      House house = (House) session1.get(House.class, Long.parseLong(add)); 

      System.out.println(house.getAddress()); 

      SessionUser.getHouses().add(house); 

      session1.merge(SessionUser);   
      tx.commit(); 
      session1.close(); 

      System.out.println(house.getAddress()); 

我编辑我的麻烦代码更简单。我只是不知道为什么这不起作用。

+0

如果您忘记提交事务并关闭会话。它将无法提交它。 –

回答

1

请提交交易并关闭会话。

String add = request.getParameter("Id"); 
     Session session1 = hiber.getSessionFactory().getCurrentSession(); 
     Transaction tx; 
     try { 
      tx = session1.beginTransaction(); 
      for (Iterator<House> iterator = SessionUser.gethouse().iterator(); iterator.hasNext();) { 
       House house = iterator.next(); 
       if (house.getProjectId() == Long.parseLong(add)) { 
        iterator.remove(); 
        session1.remove(house); 
        session1.flush(); 
       } 
      } 

      session1.merge(SessionUser); 
      tx.commit();  

     } catch (Exception e) { 
      System.out.println(e); 
     } finally {   
      System.out.println("______"); 
      session1.close(); 
     } 
+0

这并没有诀窍:/ – JonCode

+0

我希望.. SessionUser实体有很多House实体。而且,您确实通过SessionUser实体中的OneToMany关系进行级联效应定义。 “@OneToMany(cascade = ALL,mappedBy =”user“) public列表 house; –

+0

是的,我确实是这样做的,我用一种方法工作,但采用了不同的方法,但不能真正明白为什么我不能做到这一点一个工作也是如此 – JonCode