Spring Data JPA @NamedQuery

In this tutorial, we will see Spring Data JPA @NamedQuery annotation Example using Spring Boot and oracle. Also, we will see how to write multiple @NamedQuery using @NamedQueries annotation.

@NamedQuery and @NamedQueries annotations used with entity class. Using @NamedQuery annotation we can define a query. Inside @NamedQueries we can define multiple @NamedQuery.

 

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

 

and we have some record in the database as below.

Spring Data JPA @NamedQuery

 

Using @NamedQuery.

Using @NamedQueries.

Let’s see sample repository Spring Data JPA @NamedQuery.

Sample Repository Example.

Till now We have seen Spring Data JPA @NamedQuery and @NamedQueries annotations. Let’s see a complete example from scratch.

Spring Data JPA @NamedQuery and  @NamedQueries 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 – springdatanamedquery, ArtifactId – springdatanamedquery and name – springdatanamedquery) 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 –

Spring Data JPA @NamedQuery

 

Let’s see the entity for Spring Data JPA @NamedQuery using Spring Boot.

Student.java

StudentController.java

 

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

 

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

 

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

 

 

That’s all about Spring Data JPA @NamedQuery and @NamedQueries annotation Example Using Spring Boot and Oracle.

 

You may like.

 

Other Spring Data JPA and Hibernate tutorials.

 

Spring Data JPA Docs.

 

Summary –  We have seen about Spring Data JPA @NamedQuery and @NamedQueries.

 

 

Top