Search code examples
hibernatespring-data

What are scenarios for using getReferenceById instead of findById in Spring Data Repositories with Hibernate?


We are using Spring Data 3.1 with Hibernate 6.2 and are wondering when to use getReferenceById and when findById. In earlier Versions of Spring Data with Hibernate we were using getById which immediately threw an exception if an entity was not present. So in Scenarios where we expected the entity being present we used getById and in scenarios where the id could be optional we used findById. This approach seemed to have changed.

So what are scenarios for still using getReferenceById? We could just do

var user = userRepository.findById(id).orElseThrow();

everywhere instead of

var user = userRepository.getReferenceById(id);

I understand that getReferenceById returns just a proxy, but I don't see use cases where this is desirable to use.


Solution

  • Using getReference() can eliminate needless roundtrips to our database when we update entity relations.

    Few cases benefits by using getReference

    1. Delete entity
    2. Updating Entity Relations

    Nevertheless, Hibernate doesn’t follow the specification for getReference() by default to save a database roundtrip when possible. Accordingly, it doesn’t throw an exception when we retrieve entity proxies, even if they don’t exist in the database.

    It may lead to some potential bugs because it doesn't throw exception. Be careful when use it.

    Refer to this document