Hibernate 不保存对象,即使在日志中没有收到任何错误

Hibernate does not save Object even not getting any error in log

我在 db 中有一个 table。创建了一个 pojo class 以将 class 实例映射到 table。我的 class 结构是

   @Entity
    @Table(name = "example")
    class example {
     @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "ID")
        int id;
        @Column(name = "SLOT_ID")
        int slot_id;
        @Column(name = "SLOT_DATE")
        String slot_date;
        @Column(name = "HOTEL_ID")
        String hotel_id;
        @Column(name = "ROOM_TYPE_ID")
        String room_type_id;
        @Column(name = "CREATE_DATE")
        String create_date;
        @Column(name = "UPDATE_DATE")
        String update_date;
        @Column(name = "SLOT_PRICE")
        Double slot_price;
        @Column(name = "AVAILABLE_ROOMS")
        Integer available_roooms;

//rest have getter and setter method }

Hibernet 提交部分

  public void save(Example example) {

        Session session = null;
        try {
            log.info( example.toString());
            session = this.sessionFactory.openSession();
            Transaction tx = session.beginTransaction();
            session.persist(example);
            tx.commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

在日志中,我收到此日志

Hibernate: insert into example(AVAILABLE_ROOMS, CREATE_DATE, HOTEL_ID, ROOM_TYPE_ID, SLOT_DATE, SLOT_ID, SLOT_PRICE, UPDATE_DATE) values (?, ?, ?, ?, ?, ?, ?, ?)

我可以从同一个 table 中获取数据,这里是 Code snap `

session = this.sessionFactory.openSession(); 
Criteria cr = session.createCriteria(Example.class); cr.add(Restrictions.eq("id", id)); List results = cr.list();
 if(results.size()>0) 
return mapper.writeValueAsString(results.get(0)); //id is auto //incremented in table`

我在日志中没有看到任何错误,但是当我在数据库中检查时,没有任何数据 inserted.Any 提示我错过了什么?

使用此代码并测试一次

public void save(Example example) {
    Session session = null;
    Transaction tx=null;
    try {
        log.info( example.toString());
        session = this.sessionFactory.openSession();
        tx = session.beginTransaction();
        session.persist(example);
        tx.commit();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {

     if (!tx.wasCommitted()) {
     tx.rollback();
     }//not much doing but a good practice
     session.flush(); //this is where I think things will start working.
     session.close();
    }
}

关闭前调用 flush 的充分理由是 here

我认为您必须使用 session.save() 而不是 session.persist(),或者您必须按照 Viraj 的指示在事务结束时使用刷新,另请参阅此 post

What's the advantage of persist() vs save() in Hibernate?