Spring Boot JPQL Update Query with Example





Hey guys in this post, we will discuss writing a JPQL update query with Example. We will create a spring boot project step by step and connect it to the MySQL database. Follow this tutorial till the end to understand the JPQL update query.

Complete example


Let’s create a step-by-step spring boot project and create a JPQL select query. We will write a JPQL query to update a record by its name.

Read More:

  1. Check this how to write JPQL select query
  2. Check this how to write a JPQL delete query

Create database and insert sample data


Open MySQL workbench and execute the following commands

CREATE DATABASE mydb;

USE mydb;

CREATE TABLE tbl_laptops(
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    description VARCHAR(255) NOT NULL,
    brand VARCHAR(255) NOT NULL,
    price DOUBLE(10, 2) NOT NULL,
    created_at DATE NOT NULL
);

INSERT INTO tbl_laptops(name, description, brand, price, created_at)
VALUES("Dell Inspiron", "dell company laptop", "Dell", 60000.00, '2021-02-10');
INSERT INTO tbl_laptops(name, description, brand, price, created_at)
VALUES("Dell XPS", "dell company laptop", "Dell", 70000.00, '2020-12-31');
INSERT INTO tbl_laptops(name, description, brand, price, created_at)
VALUES("Macbook Air", "apple company laptop", "Apple", 85000.00, '2021-01-31');
INSERT INTO tbl_laptops(name, description, brand, price, created_at)
VALUES("Macbook Pro", "apple company laptop", "Apple", 160000.00, '2021-12-25');
INSERT INTO tbl_laptops(name, description, brand, price, created_at)
VALUES("HP", "hp company laptop", "HP", 50000.00, '2021-02-10');
INSERT INTO tbl_laptops(name, description, brand, price, created_at)
VALUES("Lenovo", "lenovo company laptop", "Lenovo", 50000.00, '2020-11-21');

SELECT * FROM tbl_laptops;

We have created a table tbl_laptops that contains 5 fields. We have inserted the sample data as well.

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 java.sql.Date;

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

import lombok.Data;

@Entity
@Table(name="tbl_laptops")
@Data
public class Laptop {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	
	private String name;
	
	private String brand;
	
	private String description;
	
	private BigDecimal price;
	
	@Column(name="created_at")
	private Date createdAt;
}

We have added @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 Repository


Create an interface LaptopRepository.java inside the in.bushansirgur.springboot.repos package and add the following content

package in.bushansirgur.springboot.repository;

import java.math.BigDecimal;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import in.bushansirgur.springboot.entity.Laptop;

@Repository
public interface LaptopRepository extends JpaRepository<Laptop, Long>{
	
	@Transactional
	@Modifying
	@Query("UPDATE Laptop SET price = :price WHERE name = :name")
	Integer updatePriceByName(BigDecimal price, String name);
}
  • @Query annotation is used to write the JPQL query. JPQL queries take field names instead of column names
  • @Modifying annotation is used whenever we writing JPQL query for modifying the records (create, update, delete)
  • JPQL query always returns either void or integer whenever we are writing a query for modifying.
  • @Transactional annotation is used whenever we are writing JPQL queries, it is from the org.springframework.transaction.annotation.Transactional package

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.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

import in.bushansirgur.springboot.repository.LaptopRepository;

@RestController
public class LaptopController {
	
	@Autowired
	private LaptopRepository lRepo;
	
	@PutMapping("/laptops/update/{price}/{name}")
	public ResponseEntity<String> updatePriceByName(@PathVariable BigDecimal price, @PathVariable String name) {
		return new ResponseEntity<String>(lRepo.updatePriceByName(price, name)+" record(s) updated.", HttpStatus.OK);
	}
}

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/update/100000.00/dell inspiron

Screenshot-2021-06-11-at-12-32-32-PM

That’s it for this post. Hope you guys like it, if so please do share this with your friends and colleagues. Also this post in your social media profiles. 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.

This Post Has One Comment

  1. Ajay K Angadi

    Dear Sir,
    Hats up to your contribution to this web tutorial ,I really liked the way you narrated the various topics in this website.Thank you very much Please solve two questions from model question paper of FSD subject which has been included for 5th sem CS Diploma course in Karnataka by DTE Bangalore.This will help may Diploma students across 174 Polytecnics in karnataka State. The questions are as follows-
    1.Develop the data access layer of the Employee Management Application to perform the database operations given below using Spring Data JPA
    Add the operation given below using Spring Data JPA:
    Update the employeeContactNumber for the given employee id.
    2.Create a RESTcontroller class to perform CRUD operations on product and corresponding request and response DTOs.
    The product class should contain three data members product name, product category, price. Use proper SpringBoot annotations.

Leave a Reply