Updating lazy loaded entity fetched with getReference()

Retrieving an entity via the getReference method doesn’t involve any database access. If one or more fields (excluding the ID field) are updated and then persist is invoked, will Hibernate retrieve the entity from the database before persisting it? Or does it persist the updated fields with just one SQL query, leaving the other fields unchanged?

Code example:

        User user = entityManager.getReference(User.class, id);

Note that getReference returns a proxy if the persistence context does not already contain an instance. Unless you’re using bytecode enhancement, as soon as you call any methods on the proxy that is not getId(), the proxy will be initialized.
In case of bytecode enhancement, it will load the entity before attempting to flush the state.

1 Like