无法在Hibernate Java中保存对象

时间:2018-04-13 20:53:30

标签: java hibernate

我是Hibernate Java的新手。我想向mySQL添加新对象。我使用保存来做它但我无法保存对象,我可以更新。我想我在hibernate.cfg.xml文件中有问题,但我无法弄明白。我在这个链接中尝试了解决方案

hibernate session.save() does not reflect in database

我将行<property name="connection.autocommit">true</property>添加到hibernate.cfg.xml但它仍然无效。怎么了?

的hibernate.cfg.xml

<session-factory>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost/Checkin</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"/>
    <mapping resource="Entities/Teacher.hbm.xml"/>
    <mapping resource="Entities/Subject.hbm.xml"/>
    <mapping resource="Entities/Student.hbm.xml"/>

这是我的主题DAO,我称之为SubjectUtil

public class SubjectUtil {
     private final SessionFactory sf = HibernateUtil.getSessionFactory();

    public List<Subject> findSubject()
    {
        List<Subject> list = new ArrayList<Subject>();
        try {
            sf.getCurrentSession().beginTransaction();
            list=sf.getCurrentSession().createCriteria(Subject.class).list();
            sf.getCurrentSession().getTransaction().commit();
            return list;

        }catch(Exception e)
        {
            return null;
        }finally {
            sf.getCurrentSession().close();
        }
}

      public boolean Save(Subject sub)
      {

          try {
              sf.getCurrentSession().beginTransaction();

              sf.getCurrentSession().save(sub);
              sf.getCurrentSession().getTransaction().commit();
              return true;
          }catch(Exception e)
          {
              sf.getCurrentSession().getTransaction().rollback();
              return false;
          }
      }
      public boolean Update(Subject sub)
      {
          try {
              sf.getCurrentSession().beginTransaction();
              sf.getCurrentSession().update(sub);
              sf.getCurrentSession().getTransaction().commit();
              return true;
          }catch(Exception e)
          {
              sf.getCurrentSession().getTransaction().rollback();
              return false;
          }
      }
}

1 个答案:

答案 0 :(得分:0)

根据休眠文档,不建议使用hibernate.connection.autocommit属性:

https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/session-configuration.html