While learning HIbernate I came across this in the Hibernate official documentation:

That is because Hibernate caches all the newly inserted Customer instances in the session-level cache.

I am aware that Hibernate caches the entities retrieved but does it cache the new ones as well?

EDIT: newly created instance like session.save(new Customer())

1 Answers

1
Ken Chan On Best Solutions
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.save(customer);
}
tx.commit();
session.close();

What the cache here means that after session.save(customer) , the customer would still in the session object and not removed before the session is closed.

It means that if you use session.get(Customer.class, id) to get a customer with an ID that is already saved before closing the session, it will not cause a SQL SELECT to retrieve this customer from database but simply return the cached customer from the session .