即使没有在日志中出现任何错误,Hibernate也不会保存Object

时间:2015-07-05 12:57:45

标签: java hibernate spring-mvc hibernate-mapping spring-annotations

我在db中有一个表。创建了一个pojo类来将类实例映射到表。我的班级结构是

   @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 (?, ?, ?, ?, ?, ?, ?, ?)

我可以从同一个表中获取数据,这是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`

我没有在日志中看到任何错误,但是当我在DB中解雇时没有插入数据。任何线索我错过了什么?

2 个答案:

答案 0 :(得分:4)

使用此代码并测试一次

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();
    }
}

在关闭之前调用齐平的充分理由是here

答案 1 :(得分:2)

我认为你必须使用session.save()而不是session.persist(),或者你必须在Viraj所指向的事务结束时使用flush,也请参考这篇文章

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