Search code examples
javahibernateormentityidentifier

What is difference between session.get() and session.byId().load() in Hibernate?


When an object is written to database and the primary identifier (id) is known, it can be retrieved by the code below:

MyObject myObject = session.get(Class<MyObject>, id);

It seems, there is another way similar to get() method:

IdentifierLoadAccess<MyObject> ila = session.byId(Class<MyObject>);
MyObject myObject = ila.load(id);

I'm looking for a scenario which clarifies differences between them and describes the reason for having two similar methods for the same job in API.

same question can be asked about session.load() and session.byId().getReference().

Edit 1:
According to API documentation:

  • session.get() and session.byId().load() return persistent instance with given identifier, or null if there is no such persistent instance.

  • session.load() and session.byId().getReference() might return a proxied instance that is initialized in demand.


Solution

  • IdentifierLoadAccess allows you to specify:

    • LockOptions
    • CacheMode

    even specifying both of them at once:

    Post post = session
    .byId( Post.class )
    .with( new LockOptions( LockMode.OPTIMISTIC_FORCE_INCREMENT) )
    .with( CacheMode.GET )
    .load( id );
    

    The same for getting a Proxy reference via getReference(id).

    So, they are more flexible than the standard get or load which only take the entity identifier.