Spring Data JPA JpaRepository getOne()

In this article, we will see about Spring Data JPA JpaRepository getOne() Example using Spring Boot and Oracle.

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

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

T getOne(ID id);

Using getOne() method we get a single record(entity) on basis of id. If we provide id null, it will throw error ” The given id must not be null”.

The getOne() throws EntityNotFoundException if no record/entity exists for given id.

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

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

Note –  The getOne() just returns a reference of the entity. All fields might contain default values.

Let’s see in below code how to use the Spring Data JPA CrudRepository getOne() method for get operation. We will see a complete example later in the post.

First, Define repository interface extending JpaRepository since getOne() defined in JpaRepository interface.

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

In ServiceImpl class we can use getOne() method as below.

package com.javatute.impl;


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

	@Autowired
	private StudentRepository studentRepository;

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

}

The calling getOne() returns a lazily fetched entity. When we say lazily fetched what does it mean?

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 see an example of Spring Data JPA JpaRepository 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 – springdatagetone, ArtifactId – springdatagetone and name – springdatagetone) 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>springdatagetone</groupId>
	<artifactId>springdatagetone</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springdatagetone</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.

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

Directory structure –

Spring Data JPA JpaRepository 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.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping(value = "/student")
public class StudentController {

	@Autowired
	private StudentService studentService;

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Student save(@RequestBody Student student) {
		Student studentResponse = (Student) studentService.saveStudent(student);
		return studentResponse;
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Student getStudent(@PathVariable int id) {
		Student studentResponse = (Student) studentService.getStudent(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 getStudent(int id);

}

StudentServiceImpl.java

package com.javatute.impl;

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 getStudent(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/{id}

http://localhost:9091/student/1
Spring Data JPA JpaRepository getOne()

See brief about Spring Data JPA Repository hierarchy as below.

Spring Data JPA JpaRepository getOne()

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

You may like.

Other Spring Data JPA and Hibernate tutorials.

Spring Data JPA getOne() docs.