Search code examples
javahibernatespring-mvchibernate-mappingspring-annotations

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


I have a single table in db . Created a pojo class to map class instance to table. my class structure is

   @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 commit part

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

in log i am getting this log

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

I am able to fetch data from same table here is 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`

I dont see any error in log but when i cheked in DB no data has been inserted.Any clue what i missed ?


Solution

  • Use this code and test once

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

    Good reason to call flush before close is here