Spring Data JPA Projection Example

In this tutorial, we will see Spring Data JPA Projection Example using Spring Boot and oracle. We will see how to implement Projection using Spring Data JPA.

Consider we have an entity called Student.java as below.

 

and we have some record in the database as below.

Spring Data JPA Projection Example

We want to fetch any single column. For example, we want all student name as below.

 

Spring Data JPA Projection Example

 

Let’s see how to define Projection for the above requirement.

Define Interface with some method.

 

Define Repository as below.

 

Generated query.

Hibernate:
select
student0_.name as col_0_0_
from
student student0_

Running below example we should able to fetch name column details as below.

Spring Data JPA Projection Example

Spring Data JPA Projection Example using  Spring Boot and Oracle.

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’ click on next.  Fill all details(GroupId – springdataprojection, ArtifactId – springdataprojection and name – springdataprojection) 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.

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

 

Let’s see the entity for Spring Data JPA Projection Example using Spring Boot.

Student.java

StudentController.java

 

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

StudentRepository.java – interface

Define Interface StudentName with method getName..

 

StudentService.java – interface

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

StudentServiceImpl.java

SpringMain.java

Note – See more details about @ComponentScan here.

JpaConfig.java

Note – See more details about @Configuration annotations here.

application.properties

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

Perform saveall operation first using below REST API.

http://localhost:9091/student/saveall

Let’s see response data for Spring Data JPA Projection Example.

Response Data.

 

http://localhost:9091/student/findallname

Spring Data JPA Projection Example

That’s all about Spring Data JPA Projection Example Using Spring Boot and oracle.

 

You may like.

 

Other Spring Data JPA and Hibernate tutorials.

 

Spring Data JPA Docs.

 

 

 

 

Top