In this source code example, we will demonstrate how to use the deleteById() method in Spring Data JPA to delete an entity by id from the database table.
The deleteById() method serves a simple purpose: to delete an entity based on its primary key. If you've ever found yourself writing custom deletion queries, you'll immediately see the value in this straightforward approach.
In this example, we will use the Product entity to save and delete to/from the MySQL database.
Maven Dependencies
First, you need to add the below dependencies to your Spring boot project:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
Create Product Entity
package net.javaguides.springdatajpacourse.entity;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
@Entity
@Table(name="products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "sku")
private String sku;
@Column(name = "name")
private String name;
@Column(name = "description")
private String description;
@Column(name = "price")
private BigDecimal price;
@Column(name = "image_url")
private String imageUrl;
@Column(name = "active")
private boolean active;
@Column(name = "date_created")
@CreationTimestamp
private Date dateCreated;
@Column(name = "last_updated")
@UpdateTimestamp
private Date lastUpdated;
// getter and setter methods
@Override
public String toString() {
return "Product{" +
"id=" + id +
", sku='" + sku + '\'' +
", name='" + name + '\'' +
", description='" + description + '\'' +
", price=" + price +
", imageUrl='" + imageUrl + '\'' +
", active=" + active +
", dateCreated=" + dateCreated +
", lastUpdated=" + lastUpdated +
'}';
}
}
ProductRepository
import net.javaguides.springdatajpacourse.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Long> {
}
Configure MySQL and Hibernate Properties
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false
spring.datasource.username=root
spring.datasource.password=Mysql@123
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
Testing deleteById() Method
Let's write a JUnit test to test deleteById() method:
import net.javaguides.springdatajpacourse.entity.Product;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import java.math.BigDecimal;
import java.util.List;
@DataJpaTest
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
class ProductRepositoryTest {
@Autowired
private ProductRepository productRepository;
protected Product getProduct1(){
Product product = new Product();
product.setName("product 1");
product.setDescription("product 1 desc");
product.setPrice(new BigDecimal(100));
product.setSku("product 1 sku");
product.setActive(true);
product.setImageUrl("product1.png");
return product;
}
@Test
void testDeleteByIdMethod(){
Product product = getProduct1();
productRepository.save(product);
// delete product by id
productRepository.deleteById(product.getId());
}
}
We are using @DataJpaTest annotation to write a JUnit test for the ProductRepository deleteById() method.@AutoConfigureTestDatabase annotation is to disable embedded in-memory database support and enable MySQL database support.
Output
Here is the output of the above JUnit test case we wrote for testing deleteById() method:
Hibernate:
insert
into
products
(active, date_created, description, image_url, last_updated, name, price, sku)
values
(?, ?, ?, ?, ?, ?, ?, ?)
Hibernate:
delete
from
products
where
id=?
Note that Spring Data JPA (Hibernate) produces the above SQL query delete an entity by id from the database table.
delete
from
products
where
id=?
A Few Notes of Caution:
Handling Non-existent IDs: If you try to delete an entity with an ID that doesn't exist, deleteById() will throw an EmptyResultDataAccessException. It's advisable to check for the existence of the record using existsById() before calling deleteById() or handle the exception gracefully.Transactional Integrity: Ensure that the deletion does not violate any database constraints. For instance, if there are related records in another table that depend on the record you're trying to delete, the operation will fail due to referential integrity constraints.
Cascade Deletes: If you've set up JPA cascading operations, deleting a parent entity might delete its children as well. Ensure you're aware of these cascade rules in your entity relationships.
Related Spring Data JPA Examples
- Spring Data JPA - save() Method Example
- Spring Data JPA - saveAll() Method Example
- Spring Data JPA - findById() Method Example
- Spring Data JPA - findAll() Method Example
- Spring Data JPA - count() Method Example
- Spring Data JPA - deleteById() Method Example
- Spring Data JPA - delete() Method Example
- Spring Data JPA - deleteAll() Method Example
- Spring Data JPA - Distinct Query Method Example
- Spring Data JPA - GreaterThan Query Method Example
- Spring Data JPA - LessThan Query Method Example
- Spring Data JPA - Containing Query Method Example
- Spring Data JPA - Like Query Method Example
- Spring Data JPA - Between Query Method Example
- Spring Data JPA - Date Range Between Query Method Example
- Spring Data JPA - In Clause Query Method Example