Spring Boot and Data JPA @NamedNativeQuery annotation with Example





Hey guys in this post, we will discuss Data JPA @NamedNativeQuery annotation with Example. We will create a spring boot project step by step and connect it to the MySQL database. This is the continuation of the previous post, please follow that post, before proceeding with this.

Complete example


Let’s create a step-by-step spring boot project and create a native query in Data JPA using @NamedNativeQuery.

Read More:

Create spring boot project


There are many different ways to create a spring boot application, you can follow the below articles to create one –

>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA

Add maven dependencies


Open pom.xml and add the following dependencies –

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>in.bushansirgur</groupId>
	<artifactId>findbyfieldname</artifactId>
	<version>v1</version>
	<name>findbyfieldname</name>
	<description>Spring boot data jpa find by field name</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

spring-boot-starter-web dependency for building web applications using Spring MVC. It uses the tomcat as the default embedded container.




spring-boot-devtools dependency for automatic reloads or live reload of applications. spring-boot-starter-data-jpa dependency is a starter for using Spring Data JPA with Hibernate. lombok dependency is a java library that will reduce the boilerplate code that we usually write inside every entity class like setters, getters, and toString()

Configure the datasource


spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=scbushan05
spring.datasource.password=scbushan05

spring.jpa.hibernate.ddl-auto=update

Create an entity class


Create Laptop.java inside the in.bushansirgur.springboot.entity package and add the following content

package in.bushansirgur.springboot.entity;

import java.math.BigDecimal;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedNativeQuery;
import javax.persistence.Table;

import in.bushansirgur.springboot.request.LaptopRequest;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Entity
@Table(name="tbl_laptops")
@Getter
@Setter
@NoArgsConstructor
@NamedNativeQuery(name = "getAllRecords", query = "select * from tbl_laptops", resultClass = Laptop.class)
public class Laptop {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	
	private String name;
	
	private String brand;
	
	private BigDecimal price;
	
	public Laptop(LaptopRequest request) {
		this.name = request.getName();
		this.price = request.getPrice();
		this.brand = request.getBrand();
	}
	
}
  • @NamedNativeQuery annotation is used to write the SQL query. We write the raw SQL query inside this annotation. The option name is used the specify the name of the method, the option query is used to write the plain SQL query, the option resultClass is used to map the records to the specific class
  • @Data annotation which is a Lombok annotation, that will automatically create setters, getters, toString(), and equals() for us.
  • @Entity is a mandatory annotation that indicates that this class is a JPA entity and is mapped with a database table.
  • @Table annotation is an optional annotation that contains the table info like table name.




  • @Id annotation is a mandatory annotation that marks a field as the primary key

Create a DAO


Create an interface LaptopDAO.java inside the in.bushansirgur.springboot.dao package and add the following content

package in.bushansirgur.springboot.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import in.bushansirgur.springboot.entity.Laptop;

@Repository
public class LaptopDAO {
	
	@PersistenceContext
    private EntityManager manager;
	
	public List<Laptop> getAll () {
		return manager.createNamedQuery("getAllRecords", Laptop.class).getResultList();
	}
}
  • @PersistenceContext handles a set of entities that hold data to be persisted in some persistence store (e.g. a database). In particular, the context is aware of the different states an entity can have (e.g. managed, detached) in relation to both the context and the underlying persistence store.
  • JPA EntityManager is used to access a database in a particular application. It is used to manage persistent entity instances, to find entities by their primary key identity, and to query over all entities.
  • createNamedQuery() method is used to call the method name which is specified in the @NamedNativeQuery annotation.

Create a Rest controller


Create LaptopController.java inside the in.bushansirgur.springboot.controller package and add the following content

package in.bushansirgur.springboot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import in.bushansirgur.springboot.dao.LaptopDAO;
import in.bushansirgur.springboot.entity.Laptop;
import in.bushansirgur.springboot.repository.LaptopRepository;

@RestController
public class LaptopController {
	
	@Autowired
	private LaptopRepository lRepo;
	
	@Autowired
	private LaptopDAO lDAO;
	
	@PostMapping("/laptops/save")
	public Laptop saveData (@RequestBody Laptop laptop) {
		return lRepo.save(laptop);
		
	}
	
	@GetMapping("/laptops")
	public List<Laptop> readData () {
		return lDAO.getAll(); 
		
	}
}

Run the app


Run the application using the below maven command –

mvn spring-boot:run

Open the browser and enter the following URL –

  • localhost:8080/laptops

Screenshot-2021-06-19-at-6-55-36-PM
That’s it for this post, I hope you guys enjoyed this post. If you did, please share this post with your friends and colleagues. Also, share this post on your social media profile. Thanks, I will see you in the next post.



Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply