Wasted time debugging ! findOne vs getOne in JPA

Chandan Kumar Barik
2 min readSep 24, 2023

--

It so happened that while I would have used findOne often, somehow in one of the method there was the use of getOne, unsure of how it would have been different from the findOne.
I happened to call this method from a new implementation that I was doing and I was getting unintended results, why ? because they work differently.

When I start debugging the code, I found that the object that I was fetching using the getOne, every attribute inside it was null. But then, the one to many relationship that I was building inside it, when I accessed it using a getter and was using in a different method, I saw there were elements inside it. I was certain that something sort of lazy loading was happening.


private String stringExample;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "columnB")
private List<ClassB> classB;

getOne :

It is mostly used for retrieving a reference (proxy) to an entity without actually loading its attributes from the database until they are accessed. It returns a proxy object that represents the entity, but the actual database query is deferred until you access a property or method that requires data from the entity.

This method is useful when you want to create associations or relationships with other entities without incurring the overhead of loading all the data for the referenced entity.

It is not suitable for cases where you need to work with the complete entity object immediately, as it may throw an exception if the entity with the given identifier doesn’t exist in the database. It doesn’t perform an actual query until you access the entity’s data.

findOne :

It is used for fetching an entity from the database with all its attributes immediately. It performs an actual database query and returns the complete entity object, or ‘null’ if the entity with the given identifier doesn’t exist.

This method is suitable when you need to work with the entity’s attributes immediately or check if an entity with a specific identifier exists in the database.

Thus, to not wonder why attributes are null while everything seems perfect in your remaining piece of code, there is data in the tables for the record you are trying to fetch, and an attribute with 1-to-many relationship of the object seems to be not null and working fine when you have fetched it through getter method, then you must be cautious of using getOne and findOne.

But worry not, the vaugue naming of getOne is now solved by bringing a different method for the same : getRefereneceById.

--

--