Reputation: 32331
I am working with Hibernate to insert the Data and also to get the Data with the same session as shown below
StudentBean st1 = new StudentBean();
st1.setSid(513);
st1.setSname("Ravi)");
st1.setTotMarks(0.0f);
Session sess = factory.openSession();
sess.persist(st1);
StudentBean st2 = (StudentBean) sess.get(StudentBean.class, 510);
System.out.println(st2.getSname());
When i used show_sql true in the hibernate configuration file , and With this lines the output is
Select Query
Hibernate: select studentbea0_.sid1 as sid1_0_0_, studentbea0_.sname1 as sname2_0_0_, studentbea0_.tot_m1 as tot3_0_0_ from student1 studentbea0_ where studentbea0_.sid1=?
Insert Query
insert into student1 (sname1, tot_m1, sid1) values (?, ?, ?)
Could anybody please tell me why the Insert operation is performed last , by the Hibernate Engine , even though Session.persist is above the get Method ??
Upvotes: 2
Views: 236
Reputation: 8144
When you call persist() the instance isn't saved to the database immediately. It is just saved in the hibernate session (first level cache.) When you call get() hibernate first checks the session for the Student with id 510, doesn't find it, so goes to the databse. This generates the select. When the session is flushed (i.e. when you call session.close()) all the instances in the session are examined and any changes are written to the database. This generates the insert. Also, if you had changed any of the attributes of 510, they would automatically be written out, generating updates.
Upvotes: 1
Reputation: 14366
Apparently Hibernate assumes that it alone owns the database you are using, and "knows" that the record in question cannot have been changed behind its back by another user of the database. Therefore your Session.get()
does not trigger an SQL SELECT
, instead the object is just returned from Hibernate's cache.
A more interesting question is why there was a SELECT
before the INSERT
. It could have to do with Hibernate populating its first-level cache, or it could be due to some preceding code you haven't shown.
Upvotes: 0