I have noticed that the INSERT statement that Hibernate sends to the database always contains the values that were held by the object when Session.save() was called. This means that if the object changes after Session.save(), then another UPDATE will be issued (instead of combining the changes into one INSERT)
Does anybody know whether it is possible to combine all changes into the one INSERT?
If not, any idea why not? (i.e. is there a good reason, or is just the case that nobody has really asked for it)
Below a simple Java class that reproduces this issue:
Code:
public class SaveThenUpdateTest {
public final static Logger log = Logger.getLogger(SaveThenUpdateTest.class);
public static void main(String[] args) {
log.info("Configuring connection");
Configuration config = new Configuration()
.addClass(A.class)
.setProperty("hibernate.connection.driver_class", "...")
.setProperty("hibernate.connection.url", "...")
.setProperty("hibernate.connection.username", "...")
.setProperty("hibernate.connection.password", "...")
;
SessionFactory f = config.buildSessionFactory();
Session s = f.openSession();
Transaction tx = s.beginTransaction();
A a = new A();
a.setValueA("valuea");
s.save(a);
a.setValueB("valueb");
log.info("Before commit");
tx.commit();
f.close();
log.info("Finished tests");
}
}
and this is what we get in the log:
Code:
INFO SaveThenUpdateTest:16 - Configuring connection
DEBUG SQL:401 - select max(id) from A
INFO SaveThenUpdateTest:33 - Before commit
DEBUG SQL:401 - insert into A (valueA, valueB, id) values (?, ?, ?)
DEBUG SQL:401 - update A set valueA=?, valueB=? where id=?
INFO SaveThenUpdateTest:36 - Finished tests