Hibernate:将数据插入DB

时间:2017-11-09 09:16:02

标签: java sql hibernate

我有这段代码,但我不知道将数据插入数据库的查询在哪里:

public boolean regNotification(Notifiche notifiche){

     Session session = HibernateUtil.openSession();
     if(isNotificationExists(notifiche)) return false;
     Transaction tx = null; 
     try {
         tx = session.getTransaction();
         tx.begin();
         session.saveOrUpdate(notifiche);
         tx.commit();
     } catch (Exception e) {
         if (tx != null) {
             tx.rollback();
         }
         e.printStackTrace();
     } finally {
         session.close();
         //System.out.println("Closing Session");
     }  
     return true;
}

2 个答案:

答案 0 :(得分:0)

这会插入数据:

dockerd

这会提交您的更改:

session.saveOrUpdate(notifiche);

您也可以使用HQL,但Hibernate的想法是使用会话和事务等对象来从SQL中抽象出来。

答案 1 :(得分:0)

我认为您的代码无法正常运行 创建会话应该是:Session session = HibernateUtil.getSessionFactory()。openSession(); 我认为其他代码行是可以的。 session.saveOrUpdate(notifiche); - >将插入(如果不存在于db中)或更新(如果存在于db中)数据到db。 希望这有帮助。

相关问题