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.
package com.javatute.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; }
and we have some record in the database as below.
Using @NamedQuery.
package com.javatute.entity; @Entity @NamedQuery(name = "Student.findByName", query = "select s from Student s where s.name = ?1") 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; }
Using @NamedQueries.
package com.javatute.entity; @Entity @NamedQueries({ @NamedQuery(name = "Student.findByName1", query = "select s from Student s where s.name = ?1"), @NamedQuery(name = "Student.findByNameAndRollNumber", query = "select s from Student s where s.name = ?1 and s.rollNumber = ?2"), @NamedQuery(name = "Student.findByNameOrRollNumber", query = "select s from Student s where s.name = ?1 or s.rollNumber = ?2") }) 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; }
Let’s see sample repository Spring Data JPA @NamedQuery.
Sample Repository Example.
package com.javatute.repository; import java.io.Serializable; import java.util.List; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.javatute.entity.Student; @Repository public interface StudentRepository extends CrudRepository<Student, Serializable> { List<Student> findByName(String name); List<Student> findByNameAndRollNumber(String name, String rollNumber); List<Student> findByNameOrRollNumber(String name, String rollNumber); }
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
<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>springdatanamedquery</groupId> <artifactId>springdatanamedquery</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springdatanamedquery</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 –
Let’s see the entity for Spring Data JPA @NamedQuery using Spring Boot.
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; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; @Entity @NamedQueries({ @NamedQuery(name = "Student.findByName1", query = "select s from Student s where s.name = ?1"), @NamedQuery(name = "Student.findByNameAndRollNumber", query = "select s from Student s where s.name = ?1 and s.rollNumber = ?2"), @NamedQuery(name = "Student.findByNameOrRollNumber", query = "select s from Student s where s.name = ?1 or s.rollNumber = ?2") }) 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 java.util.List; 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 = "/saveall", method = RequestMethod.POST) @ResponseBody public List<Student> saveAllStudents(@RequestBody List<Student> studentList) { List<Student> studentResponse = (List<Student>) studentService.saveAllStudent(studentList); return studentResponse; } @RequestMapping(value = "/findByName/{name}", method = RequestMethod.GET) @ResponseBody public List<Student> findByName(@PathVariable String name) { List<Student> studentResponse = (List<Student>) studentService.findByName(name); return studentResponse; } @RequestMapping(value = "/findByNameAndRollNumber/{name}/{rollNumber}", method = RequestMethod.GET) @ResponseBody public List<Student> findByNameAndRollNumber(@PathVariable String name, @PathVariable String rollNumber) { List<Student> studentResponse = (List<Student>) studentService.findByNameAndRollNumber(name, rollNumber); return studentResponse; } @RequestMapping(value = "/findByNameOrRollNumber/{name}/{rollNumber}", method = RequestMethod.GET) @ResponseBody public List<Student> findByNameOrRollNumber(@PathVariable String name, @PathVariable String rollNumber) { List<Student> studentResponse = (List<Student>) studentService.findByNameOrRollNumber(name, rollNumber); return studentResponse; } }
Note – See more details about @Controller and RestController here.
StudentRepository.java – interface
package com.javatute.repository; import java.io.Serializable; import java.util.List; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.javatute.entity.Student; @Repository public interface StudentRepository extends CrudRepository<Student, Serializable> { List<Student> findByName(String name); List<Student> findByNameAndRollNumber(String name, String rollNumber); List<Student> findByNameOrRollNumber(String name, String rollNumber); }
StudentService.java – interface
package com.javatute.service; import java.util.List; import org.springframework.stereotype.Component; import com.javatute.entity.Student; @Component public interface StudentService { public List<Student> saveAllStudent(List<Student> studentList); List<Student> findByName(String name); List<Student> findByNameAndRollNumber(String name, String rollNumber); List<Student> findByNameOrRollNumber(String name, String rollNumber); }
Note – See here more about @Component, @Controller, @Service and @Repository annotations here.
StudentServiceImpl.java
package com.javatute.impl; import java.util.List; 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 List<Student> saveAllStudent(List<Student> studentList) { List<Student> response = (List<Student>) studentRepository.saveAll(studentList); return response; } @Transactional(readOnly = true) public List<Student> findByName(String name) { List<Student> studentResponse = studentRepository.findByName(name); return studentResponse; } @Transactional(readOnly = true) public List<Student> findByNameAndRollNumber(String name, String rollNumber) { List<Student> studentResponse = studentRepository.findByNameAndRollNumber(name, rollNumber); return studentResponse; } @Transactional(readOnly = true) public List<Student> findByNameOrRollNumber(String name, String rollNumber) { List<Student> studentResponse = studentRepository.findByNameOrRollNumber(name, rollNumber); return studentResponse; } }
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); } }
Note – 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 { }
Note – 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.properties.hibernate.format_sql=true spring.jpa.hibernate.ddl-auto =create spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect server.port = 9091 #show sql values logging.level.org.hibernate.type.descriptor.sql=trace #hibernate.show_sql = true #spring.jpa.hibernate.logging.level.sql =FINE #show sql statement #logging.level.org.hibernate.SQL=debug
Let’s run the SpringMain class(run as java application).
Perform saveall operation first using below REST API.
http://localhost:9091/student/saveall
[ { "name": "john", "rollNumber": "120", "university":"rgtu" }, { "name": "mark", "rollNumber": "121", "university":"rgtu" }, { "name": "aric", "rollNumber": "123", "university":"rgtu" }, { "name": "hira", "rollNumber": "124", "university":"rgtu" } ]
Response Data.
[ { "id": 1, "name": "john", "rollNumber": "120", "university": "rgtu" }, { "id": 2, "name": "mark", "rollNumber": "121", "university": "rgtu" }, { "id": 3, "name": "aric", "rollNumber": "123", "university": "rgtu" }, { "id": 4, "name": "hira", "rollNumber": "124", "university": "rgtu" } ]
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.
- Spring Data JPA greater than Example
- Spring Data JPA less than Example
- Spring Data JPA IsNull Example Using Spring Boot
- Spring Data findById() Vs getOne()
- Spring Data JPA CrudRepository findById()
- Spring Data JPA JpaRepository getOne()
- Spring Data CrudRepository saveAll() and findAll().
- Spring Data CrudRepository existsById()
- Spring Data JPA delete() vs deleteInBatch()
- Spring Data JPA deleteAll() Vs deleteAllInBatch()
- Spring Data JPA JpaRepository deleteAllInBatch()
- Spring Data JPA deleteInBatch() Example
- Spring Data JPA JpaRepository saveAndFlush() Example
- Spring Data JPA CrudRepository count() Example
- Spring Data JPA CrudRepository delete() and deleteAll()
- Spring Data JPA CrudRepository deleteById() Example
- CrudRepository findAllById() Example Using Spring Boot
- Spring Data CrudRepository save() Method.
- Sorting in Spring Data JPA using Spring Boot.
- Spring Data JPA example using spring boot.
- Spring Data JPA and its benefit.
Other Spring Data JPA and Hibernate tutorials.
- @Version Annotation Example In Hibernate.
- Hibernate Validator Constraints Example Using Spring Boot.
- @Temporal Annotation Example In Hibernate/Jpa Using Spring Boot.
- Hibernate Table Per Concrete Class Spring Boot.
- Hibernate Table Per Subclass Inheritance Spring Boot.
- Hibernate Single Table Inheritance using Spring Boot.
- One To One Mapping Annotation Example in Hibernate/JPA using Spring Boot and Oracle.
- One To One Bidirectional Mapping Example In Hibernate/JPA Using Spring Boot and Oracle.
- One To Many Mapping Annotation Example In Hibernate/JPA Using Spring Boot And Oracle.
- Many To One Unidirectional Mapping In Hibernate/JPA Annotation Example Using Spring Boot and Oracle.
- One To Many Bidirectional Mapping In Hibernate/JPA Annotation Example Using Spring Boot and Oracle.
- Many To Many Mapping Annotation Example In Hibernate/JPA Using Spring Boot And
Spring Data JPA Docs.
Summary – We have seen about Spring Data JPA @NamedQuery and @NamedQueries.