Spring Data findById() Vs getOne()

In this article, we will see about Spring Data findById() Vs getOne() Example using Spring Boot and Oracle. First, we will see difference between findById() and getOne() in brief later we will see all points in details.

Let’s see some difference between findById() and getOne() methods.

findById() getOne()
1. The findById() method is available in CrudRepository interface. 1. The getOne() method is available in JpaRepositpry interface.
2. The findById() method will return null if the record doesn’t exist in the database. 2. The getOne() method throw EntityNotFoundException if the record doesn’t exist in the database.
3. Internally findById() method use EntityManger find() method. 3. Internally getOne() method use EntityManger getReference() method.
4. Calling findById() returns an eagerly fetched entity. 4. Calling getOne() returns a lazily fetched entity.
5. The findById() methods return actual objects and entity fields will contain the value from the database.  5. The getOne() returns a reference of the entity. All fields may contain default values.

Note – Point 4 and 5 will be discussed in details later in this post.

Let’s see all points in details.

The findById() method is used to retrieves an entity by its id and it is available in CrudRepository interface. The findById() method has been defined as below.

Optional<T> findById(ID id);

Note – Optional is a class introduced in java 8.

The getOne() method also used to retrieves an entity based on id and it is available in JpaRepository interface. The getOne() method has been defined as below.

T getOne(ID id);

Internally findById() method use EntityManger’s find() method(as below).

 

Internally getOne() method use EntityManger getReference() method(as below).

The calling findById() returns an eagerly fetched entity whereas Calling getOne() returns a lazily fetched entity. When we say eagerly or lazily fetched what does it mean?

Optional<Student> studentResponse = studentRepository.findById(id);

In the above case(findById()), studentResponse will contain values for all fields.

Student studentResponse = studentRepository.getOne(id);

In the above case(getOne()), studentResponse will contain default values for all fields.

For example, consider we have below entity.

In the above entity, we have id, name, rollNmuber and university fields and also we have corresponding getter and setter. In this scenario lazily fetched means when below code will execute studentResponse reference would have 0 or null values for fields.

Student studentResponse = studentRepository.getOne(id);

In the above screenshot, we can see we have studentResponse reference but all fields have null as a value. So when fields will get initialized? The answer is on-demand i.e in our case while deserialization or when any getter is called.

Hope this makes sense.

Let’s come to findById() method. It returns an eagerly fetched entity that means when below code

Optional<Student> studentResponse = studentRepository.findById(id);

will execute studentResponse will contain actual student object that means all fields would be initialized with actual values.

 

So in both cases, findById() and getOne() below query

Hibernate: select student0_.id as id1_0_0_, student0_.name as name2_0_0_, student0_.roll_number as roll_number3_0_0_, student0_.university as university4_0_0_ from student student0_ where student0_.id=?

will get fired only difference is in case of findById() when line number 10 (Optional<Student> studentResponse = studentRepository.findById(id);) will execute then the query will get fired but in case of getOne() when line 14 (String name = studentResponse.getName();)  will execute then the query will get fired.

 

 

Entity level changes in case of findById() and getOne() method. Suppose we have an entity called Student.java as below.

Student.java case of finById().

Student.java case of getOne().

 

Note – If we don’t add @JsonIgnoreProperties(value={“hibernateLazyInitializer”,”handler”,”fieldHandler”}) with entity Student.java while using getOne() we might get below exception.

Type definition error: [simple type, class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)

 

For using findById() and getOne() we need to define our repository by extending JpaRepository.

 

ServiceImpl implementation.

 

 

Let’s see an example of Spring Data findById() Vs getOne() method Example.

 

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’ click on next.  Fill all details(GroupId – springdatafindbyidvsgetone, ArtifactId – springdatafindbyidvsgetone and name – springdatafindbyidvsgetone) and click on finish. Keep packaging as the jar.

Modify pom.xml

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

The directory structure of Spring Data JPA findById() Vs  getOne() example.

If you see any error for oracle dependency then follow these steps.

Directory structure –

Spring Data findById() Vs getOne()

 

Spring Data findById() Vs getOne().

Student.java

StudentController.java

Note – Add @JsonIgnoreProperties(value={“hibernateLazyInitializer”,”handler”,”fieldHandler”}) with entity else you might get below exception.

Type definition error: [simple type, class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)

 

Note – See more details about @Controller and RestController here.

StudentRepository.java – interface

StudentService.java – interface

 

StudentServiceImpl.java

Note – See more about @Component, @Controller, @Service and @Repository annotations here.

SpringMain.java

See more details about @ComponentScan here.

JpaConfig.java

 

See more details about @Configuration annotations here.

application.properties

Let’s run the SpringMain class(run as java application).

Perform save operation first using below REST API.

http://localhost:9091/student/save

Request Data –

Response data –

 

 

Get operation.

API -http://localhost:9091/student/findbyid/{id}

http://localhost:9091/student/findbyid/1

Spring Data findById() Vs getOne()

Test another API.

 

API -http://localhost:9091/student/getone/{id}

http://localhost:9091/student/getone/1

Spring Data findById() Vs getOne()

See brief about Spring Data JPA Repository hierarchy as below.

Spring Data findById() Vs getOne()

 

That’s all about Spring Data findById() Vs getOne() example using Spring Boot and Oracle.

 

You may like.

Other Spring Data JPA and Hibernate tutorials.

Spring Data JPA getOne() docs and findById() docs.

Spring Data findById() Vs getOne()

 

Top