In the previous post we saw the real difference between the load and get methods of the session. We saw that load() works with proxies and get() works with actual database entities.But this behaviour changes completely when the persistence context comes into picture.
Same is the case if we reverse the calling order:
static void loadGet() { Session session = sessionFactory.openSession(); Entity loadEntity = (Entity) session.load(Entity.class, 1); System.out.println("Entity 1: " + loadEntity.getClass()); Entity getEntity = (Entity) session.get(Entity.class, 1); System.out.println("Entity 2: " + getEntity.getClass()); session.close(); }The code is more or less same as the previous post. Instead of two different rows we load the same row twice using load first and then get.The output is as below:
Entity 1: class com.model.Entity$$EnhancerByCGLIB$$b82499d4 ... 3093 [main] DEBUG org.hibernate.SQL - select entity0_.id as id0_0_, entity0_.DA TA as DATA0_0_ from Entity entity0_ where entity0_.id=? Entity 2: class com.model.Entity$$EnhancerByCGLIB$$b82499d4And what do we see ?? get is also pointing to a proxy object. It is in fact referring to the same proxy object that load returned. For the load call Hibernate created a proxy. After this the get call was made which executed a select SQL query, but instead of creating a separate entity object, it simply populated the proxy object and returned the same.
Same is the case if we reverse the calling order:
3093 [main] DEBUG org.hibernate.SQL - select entity0_.id as id0_0_, entity0_.DA TA as DATA0_0_ from Entity entity0_ where entity0_.id=? ... Entity 1: class com.model.Entity ... Entity 2: class com.model.EntityThis time get() is called first. Hibernate looks for the entity in the persistence cache and does not find it. It then executes the select query, creates an entity object and returns it. After this when the load() method is executed, it finds the entity in the persistence cache and returns the same reference. In the next post we shall check the impact on object associations we load or get it.
No comments:
Post a Comment