Spring Data JPA Named Parameters

In this tutorial, we will see Spring Data JPA Named Parameters Example using Spring Boot and Oracle. We will see how to write the query using Named Parameters.

@Param and @Query annotations used to define Named Parameters.

Let’s see how to define the Query method(Query creation from method names) using Spring Data JPA Named Parameters.

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

 

and we have some record in the database as below.

Spring Data JPA Named Parameters

 

Query method using Spring Data JPA Named Parameters.

@Query("select s from Student s where s.name = :name")
List<Student> findByName(@Param("name") String name);

@Query("select s from Student s where s.name = :name and s.rollNumber = :rollNumber")
List<Student> findByNameAndRollNumber(@Param("name") String name, @Param("rollNumber") String rollNumber);

@Query("select s from Student s where s.name = :name or s.rollNumber = :rollNumber")
List<Student> findByNameOrRollNumber(@Param("name") String name, @Param("rollNumber") String rollNumber);

Repository Example.

 

Spring Data JPA Named Parameters 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 – springdatanamedparameter, ArtifactId – springdatanamedparameter and name – springdatanamedparameter) 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.

Directory structure –

 

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

Student.java

StudentController.java

Service layer for Spring Data JPA Named Parameters.

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

StudentRepository.java – interface

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

 

Response Data.

 

http://localhost:9091/student/findByName/john

Spring Data JPA Named Parameters

 

http://localhost:9091/student/findByNameAndRollNumber/john/120

Spring Data JPA Named Parameters

 

http://localhost:9091/student/findByNameOrRollNumber/john/121

 

 

That’s all about Spring Data JPA Named Parameters Example Using Spring Boot and Oracle.

 

You may like.

 

Other Spring Data JPA and Hibernate tutorials.

 

Spring Data JPA Docs.

 

 

 

 

Top