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.

Spring Data JPA Interview Questions and Answers
How to write a custom method in the repository in Spring Data JPA

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).

	public Optional<T> findById(ID id) {
 
		// some more code
 
		if (metadata == null) {
		return Optional.ofNullable(em.find(domainType, id));
		}
 
                //some more code
 
		return Optional.ofNullable(type == null ? em.find(domainType, id, hints) : em.find(domainType, id, type, hints));
	}

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

	public T getOne(ID id) {
		return em.getReference(getDomainClass(), id);
	}

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.

@Entity
public class Student {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

	@Column(name = "name")
	private String name;

	@Column(name = "roll_number")
	private String rollNumber;

	@Column(name = "university")
	String university;
        //getter & setter
}

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.

package com.javatute.impl;

@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentRepository studentRepository;
	
	@Transactional
	public Student findById(int id) {
		Optional<Student> studentResponse = studentRepository.findById(id);
		Student student = studentResponse.get();
		return student;
	}

	@Transactional
	public Student getOne(int id) {
		Student studentResponse = studentRepository.getOne(id);
		String name = studentResponse.getName();
		return studentResponse;
	}

}

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().

package com.javatute.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Student {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

	@Column(name = "name")
	private String name;

	@Column(name = "roll_number")
	private String rollNumber;

	@Column(name = "university")
	String university;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getRollNumber() {
		return rollNumber;
	}

	public void setRollNumber(String rollNumber) {
		this.rollNumber = rollNumber;
	}

	public String getUniversity() {
		return university;
	}

	public void setUniversity(String university) {
		this.university = university;
	}

}

Student.java case of getOne().

package com.javatute.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@Entity
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})
public class Student {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

	@Column(name = "name")
	private String name;

	@Column(name = "roll_number")
	private String rollNumber;

	@Column(name = "university")
	String university;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getRollNumber() {
		return rollNumber;
	}

	public void setRollNumber(String rollNumber) {
		this.rollNumber = rollNumber;
	}

	public String getUniversity() {
		return university;
	}

	public void setUniversity(String university) {
		this.university = university;
	}

}

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.

package com.javatute.repository;

import java.io.Serializable;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.javatute.entity.Student;

@Repository
public interface StudentRepository extends JpaRepository<Student, Serializable> {

}

ServiceImpl implementation.

package com.javatute.impl;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.javatute.entity.Student;
import com.javatute.repository.StudentRepository;
import com.javatute.service.StudentService;

@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentRepository studentRepository;

	@Transactional
	public Student saveStudent(Student student) {
		Student response = studentRepository.save(student);
		return response;
	}
	
	@Transactional
	public Student findById(int id) {
		Optional<Student> studentResponse = studentRepository.findById(id);
		Student student = studentResponse.get();
		return student;
	}

	@Transactional
	public Student getOne(int id) {
		Student studentResponse = studentRepository.getOne(id);
		return studentResponse;
	}

}

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

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>springdatafindbyidvsgetone</groupId>
	<artifactId>springdatafindbyidvsgetone</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springdatafindbyidvsgetone</name>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>

		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
		</dependency>

	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>

			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<fork>true</fork>
					<executable>C:\Program Files\Java\jdk1.8.0_131\bin\javac.exe</executable>
				</configuration>
			</plugin>


		</plugins>
	</build>
</project>

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()

Student.java

package com.javatute.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})
public class Student {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

	@Column(name = "name")
	private String name;

	@Column(name = "roll_number")
	private String rollNumber;

	@Column(name = "university")
	String university;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getRollNumber() {
		return rollNumber;
	}

	public void setRollNumber(String rollNumber) {
		this.rollNumber = rollNumber;
	}

	public String getUniversity() {
		return university;
	}

	public void setUniversity(String university) {
		this.university = university;
	}

}

StudentController.java

package com.javatute.impl;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.javatute.entity.Student;
import com.javatute.repository.StudentRepository;
import com.javatute.service.StudentService;

@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentRepository studentRepository;

	@Transactional
	public Student saveStudent(Student student) {
		Student response = studentRepository.save(student);
		return response;
	}
	
	@Transactional
	public Student findById(int id) {
		Optional<Student> studentResponse = studentRepository.findById(id);
		Student student = studentResponse.get();
		return student;
	}

	@Transactional
	public Student getOne(int id) {
		Student studentResponse = studentRepository.getOne(id);
		return studentResponse;
	}

}

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

package com.javatute.repository;

import java.io.Serializable;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.javatute.entity.Student;

@Repository
public interface StudentRepository extends JpaRepository<Student, Serializable> {

}

StudentService.java – interface

package com.javatute.service;

import org.springframework.stereotype.Component;

import com.javatute.entity.Student;

@Component
public interface StudentService {
	public Student saveStudent(Student student);

	public Student findById(int id);

	public Student getOne(int id);

}

StudentServiceImpl.java

package com.javatute.impl;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.javatute.entity.Student;
import com.javatute.repository.StudentRepository;
import com.javatute.service.StudentService;

@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentRepository studentRepository;

	@Transactional
	public Student saveStudent(Student student) {
		Student response = studentRepository.save(student);
		return response;
	}
	
	@Transactional
	public Student findById(int id) {
		Optional<Student> studentResponse = studentRepository.findById(id);
		Student student = studentResponse.get();
		return student;
	}

	@Transactional
	public Student getOne(int id) {
		Student studentResponse = studentRepository.getOne(id);
		return studentResponse;
	}

}

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

SpringMain.java

package com.javatute.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = "com.*")
@EntityScan("com.javatute.entity")
public class SpringMain {
	public static void main(String[] args) {

		SpringApplication.run(SpringMain.class, args);
	}

}

See more details about @ComponentScan here.

JpaConfig.java

package com.javatute.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@Configuration
@EnableJpaRepositories(basePackages = "com.javatute.repository")
public class JpaConfig {

}

See more details about @Configuration annotations here.

application.properties

# Connection url for the database
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=SYSTEM
spring.datasource.password=oracle2
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
# Show or not log for each sql query
spring.jpa.show-sql = true
 
 
spring.jpa.hibernate.ddl-auto =create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
 
server.port = 9091

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 –

 {

        "name": "Hiteshdo",
        "rollNumber": "0126CS01",
        "university": "rgtu"
}

Response data –

{
    "id": 1,
    "name": "Hiteshdo",
    "rollNumber": "0126CS01",
    "university": "rgtu"
}

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

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.