2

I am trying to save a object to database but it's not getting saved into the database.

UserDetails.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="USER_DETAILS")
public class UserDetails {

    @Id @GeneratedValue()
    @Column(name="USER_ID")
    private int userId;

    @Column(name="USER_NAME")
    private String userName;

    //...getter and setters

}

App.java

public class App {

    public static void main(String[] args) {
        UserDetails user = new UserDetails();
        user.setUserName("abc");

        SessionFactory factory = new Configuration().configure().buildSessionFactory();
        Session session = factory.openSession();

        Object o = session.save(user);
        System.out.println("User saved with id - " +o);
        System.out.println("HashCode of session 1st "+session.hashCode());
        session.close();

        session = factory.openSession();
        System.out.println("HashCode of session 2nd "+session.hashCode());

        UserDetails user1 =(UserDetails)session.get(UserDetails.class,Integer.valueOf(o.toString()));
        System.out.println(user1.getUserName());

        session.close();



    }
}

Logs:

Hibernate: insert into USER_DETAILS (USER_ID, USER_NAME) values (default, ?)
Hibernate: values identity_val_local()
User saved with id - 1
HashCode of session 1st 9299042
HashCode of session 2nd 12206609
Hibernate: select userdetail0_.USER_ID as USER1_0_0_, userdetail0_.USER_NAME as USER2_0_0_ from USER_DETAILS userdetail0_ where userdetail0_.USER_ID=?
abc

I am not using the transaction and I know if I put the session.save code within session.beginTransaction() and session.getTransaction().commit() the data will be saved in database. But as I am also doing a session.get on the ID which I am getting while doing session.save() how am I getting the object back?

If it's first level cache then how .. because I am also closing the session and opening a new session.I have also not configured any second level cache.

Please provide valuable inputs.

Mudit Shukla
  • 814
  • 2
  • 6
  • 16
  • 1
    possible duplicate of [What is First and Second Level caching in Hibernate?](http://stackoverflow.com/questions/337072/what-is-first-and-second-level-caching-in-hibernate) – Peter Bratton Mar 11 '14 at 13:32

1 Answers1

0

The logs show that, despite the lack of visible transaction, the object is inserted in the database and then read afterwards. Your are probably in a case of auto-commit or at least, since hibernate has flushed changes in the database, they are visible from the same sql connection (even if commit has not been done).