在本教程中,我们将学习如何使用带有示例的deleteById()
方法提供的SpringData-CrudRepository
接口
顾名思义,deleteById
()
方法允许我们通过id从数据库表中删除实体。它属于Spring Data定义的CrudRepository
接口。
<?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.6.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>net.javaguides</groupId>
<artifactId>spring-data-jpa-course</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-data-jpa-course</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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>
</plugin>
</plugins>
</build>
</project>
首先创建一个Product
实体,用于保存和从数据库中删除:
package net.javaguides.springdatajpacourse.entity;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.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;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
@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
,它扩展了CrudRepository
接口。众所周知,CrudRepository
接口提供了deleteById()
方法,因此我们的ProductRepository
界面应该扩展到CrudRepository
,以获取其所有方法:
import net.javaguides.springdatajpacourse.entity.Product;
import org.springframework.data.repository.CrudRepository;
public interface ProductRepository extends CrudRepository<Product, Long> {
}
在本例中,让我们使用MySQL数据库存储和检索数据,并使用Hibernate属性创建和删除表。
打开application.properties
文件并向其中添加以下配置:
spring.datasource.url=jdbc:mysql://localhost:3306/ecommerce?useSSL=false
spring.datasource.username=root
spring.datasource.password=Mysql@123
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
在运行Spring引导应用程序之前,请确保您将创建电子商务数据库。
此外,根据您机器上的MySQL安装更改MySQL用户名和密码。
为了测试deleteById()
方法,我们将在Spring引导应用程序启动时使用CommandLineRunner.run()
法执行测试代码:
import net.javaguides.springdatajpacourse.entity.Product;
import net.javaguides.springdatajpacourse.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.math.BigDecimal;
import java.util.Date;
@SpringBootApplication
public class SpringDataJpaCourseApplication implements CommandLineRunner{
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringDataJpaCourseApplication.class, args);
}
@Autowired
private ProductRepository productRepository;
@Override
public void run(String... args) throws Exception {
Product product = new Product();
product.setName("product 1");
product.setDescription("product 1 desc");
product.setPrice(new BigDecimal(100));
product.setDateCreated(new Date());
product.setLastUpdated(new Date());
product.setSku("product 1 sku");
product.setActive(true);
product.setImageUrl("product1.png");
productRepository.save(product);
// DELETE PRODUCT BY ID
productRepository.deleteById(product.getId());
}
}
完成Spring引导应用程序后,您可以在控制台中看到Hibernate生成的SQL语句。请注意,deleteById()
方法首先从该数据库表中按id获取实体,然后使用实体id(主键)进行删除,因此您可以在控制台中看到selectSQL语句。
Hibernate:
insert
into
products
(active, date_created, description, image_url, last_updated, name, price, sku)
values
(?, ?, ?, ?, ?, ?, ?, ?)
Hibernate:
select
product0_.id as id1_0_0_,
product0_.active as active2_0_0_,
product0_.date_created as date_cre3_0_0_,
product0_.description as descript4_0_0_,
product0_.image_url as image_ur5_0_0_,
product0_.last_updated as last_upd6_0_0_,
product0_.name as name7_0_0_,
product0_.price as price8_0_0_,
product0_.sku as sku9_0_0_
from
products product0_
where
product0_.id=?
Hibernate:
delete
from
products
where
id=?
型
INSERT SQL语句以保存实体:
insert
into
products
(active, date_created, description, image_url, last_updated, name, price, sku)
values
(?, ?, ?, ?, ?, ?, ?, ?)
DELETE SQL语句按id删除实体:
delete
from
products
where
id=?
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2021/12/spring-data-deletebyid-method.html
内容来源于网络,如有侵权,请联系作者删除!