Spring Boot 數(shù)據(jù)訪問(wèn)與數(shù)據(jù)庫(kù)集成的應(yīng)用場(chǎng)景解析
Spring Boot 數(shù)據(jù)訪問(wèn)與數(shù)據(jù)庫(kù)集成
18.1 學(xué)習(xí)目標(biāo)與重點(diǎn)提示
學(xué)習(xí)目標(biāo):掌握Spring Boot數(shù)據(jù)訪問(wèn)與數(shù)據(jù)庫(kù)集成的核心概念與使用方法,包括Spring Boot數(shù)據(jù)訪問(wèn)的基本方法、Spring Boot與MySQL的集成、Spring Boot與H2的集成、Spring Boot與MyBatis的集成、Spring Boot與JPA的集成、Spring Boot的事務(wù)管理、Spring Boot的實(shí)際應(yīng)用場(chǎng)景,學(xué)會(huì)在實(shí)際開(kāi)發(fā)中處理數(shù)據(jù)庫(kù)訪問(wèn)問(wèn)題。
重點(diǎn):Spring Boot數(shù)據(jù)訪問(wèn)的基本方法、Spring Boot與MySQL的集成、Spring Boot與H2的集成、Spring Boot與MyBatis的集成、Spring Boot與JPA的集成、Spring Boot的事務(wù)管理、Spring Boot的實(shí)際應(yīng)用場(chǎng)景。
18.2 Spring Boot數(shù)據(jù)訪問(wèn)概述
Spring Boot數(shù)據(jù)訪問(wèn)是指使用Spring Boot進(jìn)行數(shù)據(jù)庫(kù)操作的方法。
18.2.1 數(shù)據(jù)訪問(wèn)的定義
定義:數(shù)據(jù)訪問(wèn)是指使用Spring Boot進(jìn)行數(shù)據(jù)庫(kù)操作的方法。
作用:
- 實(shí)現(xiàn)數(shù)據(jù)庫(kù)的增刪改查。
- 實(shí)現(xiàn)事務(wù)管理。
- 實(shí)現(xiàn)數(shù)據(jù)的持久化。
? 結(jié)論:數(shù)據(jù)訪問(wèn)是指使用Spring Boot進(jìn)行數(shù)據(jù)庫(kù)操作的方法,作用是實(shí)現(xiàn)數(shù)據(jù)庫(kù)的增刪改查、事務(wù)管理、數(shù)據(jù)的持久化。
18.2.2 數(shù)據(jù)訪問(wèn)的常用組件
定義:數(shù)據(jù)訪問(wèn)的常用組件是指Spring Boot提供的數(shù)據(jù)訪問(wèn)組件。
組件:
- JdbcTemplate:用于JDBC操作。
- JPA:用于JPA操作。
- MyBatis:用于MyBatis操作。
- Hibernate:用于Hibernate操作。
? 結(jié)論:數(shù)據(jù)訪問(wèn)的常用組件包括JdbcTemplate、JPA、MyBatis、Hibernate。
18.3 Spring Boot與MySQL的集成
Spring Boot與MySQL的集成是最常用的數(shù)據(jù)訪問(wèn)方法之一。
18.3.1 集成MySQL的步驟
定義:集成MySQL的步驟是指使用Spring Boot與MySQL集成的方法。
步驟:
- 在pom.xml文件中添加MySQL依賴(lài)。
- 在application.properties或application.yml文件中配置MySQL連接信息。
- 創(chuàng)建實(shí)體類(lèi)。
- 創(chuàng)建Repository接口。
- 創(chuàng)建控制器類(lèi)。
- 測(cè)試應(yīng)用。
示例:
pom.xml文件中的MySQL依賴(lài):
<dependencies>
<!-- Web依賴(lài) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Data JPA依賴(lài) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL依賴(lài) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 測(cè)試依賴(lài) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>application.properties文件中的MySQL連接信息:
# 服務(wù)器端口 server.port=8080 # 數(shù)據(jù)庫(kù)連接信息 spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=root spring.datasource.password=123456 # JPA配置 spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
實(shí)體類(lèi):
import javax.persistence.*;
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String productId;
private String productName;
private double price;
private int sales;
public Product() {
}
public Product(String productId, String productName, double price, int sales) {
this.productId = productId;
this.productName = productName;
this.price = price;
this.sales = sales;
}
// Getter和Setter方法
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getSales() {
return sales;
}
public void setSales(int sales) {
this.sales = sales;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", productId='" + productId + '\'' +
", productName='" + productName + '\'' +
", price=" + price +
", sales=" + sales +
'}';
}
}Repository接口:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findBySalesGreaterThan(int sales);
}控制器類(lèi):
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductRepository productRepository;
@GetMapping("/")
public List<Product> getAllProducts() {
return productRepository.findAll();
}
@PostMapping("/")
public Product addProduct(@RequestBody Product product) {
return productRepository.save(product);
}
@GetMapping("/top-selling")
public List<Product> getTopSellingProducts(@RequestParam int topN) {
List<Product> products = productRepository.findBySalesGreaterThan(0);
products.sort((p1, p2) -> p2.getSales() - p1.getSales());
if (products.size() > topN) {
return products.subList(0, topN);
}
return products;
}
}測(cè)試類(lèi):
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest
class ProductApplicationTests {
@Autowired
private ProductController productController;
@Test
void contextLoads() {
}
@Test
void testGetAllProducts() {
List<Product> products = productController.getAllProducts();
assertEquals(5, products.size());
}
@Test
void testAddProduct() {
Product product = new Product("P006", "平板", 2000.0, 70);
Product addedProduct = productController.addProduct(product);
assertEquals("P006", addedProduct.getProductId());
}
@Test
void testGetTopSellingProducts() {
List<Product> topSellingProducts = productController.getTopSellingProducts(3);
assertEquals(3, topSellingProducts.size());
assertEquals("P004", topSellingProducts.get(0).getProductId());
assertEquals("P005", topSellingProducts.get(1).getProductId());
assertEquals("P001", topSellingProducts.get(2).getProductId());
}
}? 結(jié)論:集成MySQL的步驟包括添加MySQL依賴(lài)、配置MySQL連接信息、創(chuàng)建實(shí)體類(lèi)、創(chuàng)建Repository接口、創(chuàng)建控制器類(lèi)、測(cè)試應(yīng)用。
18.4 Spring Boot與H2的集成
Spring Boot與H2的集成是用于開(kāi)發(fā)和測(cè)試的常用方法之一。
18.4.1 集成H2的步驟
定義:集成H2的步驟是指使用Spring Boot與H2集成的方法。
步驟:
- 在pom.xml文件中添加H2依賴(lài)。
- 在application.properties或application.yml文件中配置H2連接信息。
- 創(chuàng)建實(shí)體類(lèi)。
- 創(chuàng)建Repository接口。
- 創(chuàng)建控制器類(lèi)。
- 測(cè)試應(yīng)用。
示例:
pom.xml文件中的H2依賴(lài):
<dependencies>
<!-- Web依賴(lài) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Data JPA依賴(lài) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- H2數(shù)據(jù)庫(kù)依賴(lài) -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 測(cè)試依賴(lài) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>application.properties文件中的H2連接信息:
# 服務(wù)器端口 server.port=8080 # 數(shù)據(jù)庫(kù)連接信息 spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password # JPA配置 spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true # H2數(shù)據(jù)庫(kù)控制臺(tái) spring.h2.console.enabled=true spring.h2.console.path=/h2-console
實(shí)體類(lèi)、Repository接口、控制器類(lèi)、測(cè)試類(lèi)與集成MySQL的示例相同。
? 結(jié)論:集成H2的步驟包括添加H2依賴(lài)、配置H2連接信息、創(chuàng)建實(shí)體類(lèi)、創(chuàng)建Repository接口、創(chuàng)建控制器類(lèi)、測(cè)試應(yīng)用。
18.5 Spring Boot與MyBatis的集成
Spring Boot與MyBatis的集成是常用的數(shù)據(jù)訪問(wèn)方法之一。
18.5.1 集成MyBatis的步驟
定義:集成MyBatis的步驟是指使用Spring Boot與MyBatis集成的方法。
步驟:
- 在pom.xml文件中添加MyBatis依賴(lài)。
- 在application.properties或application.yml文件中配置MyBatis連接信息。
- 創(chuàng)建實(shí)體類(lèi)。
- 創(chuàng)建Mapper接口。
- 創(chuàng)建Mapper XML文件。
- 創(chuàng)建控制器類(lèi)。
- 測(cè)試應(yīng)用。
示例:
pom.xml文件中的MyBatis依賴(lài):
<dependencies>
<!-- Web依賴(lài) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis依賴(lài) -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
<!-- MySQL依賴(lài) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 測(cè)試依賴(lài) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>application.properties文件中的MyBatis連接信息:
# 服務(wù)器端口 server.port=8080 # 數(shù)據(jù)庫(kù)連接信息 spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=root spring.datasource.password=123456 # MyBatis配置 mybatis.mapper-locations=classpath:mapper/*.xml mybatis.type-aliases-package=com.example.demo.entity
實(shí)體類(lèi):
public class Product {
private Long id;
private String productId;
private String productName;
private double price;
private int sales;
public Product() {
}
public Product(String productId, String productName, double price, int sales) {
this.productId = productId;
this.productName = productName;
this.price = price;
this.sales = sales;
}
// Getter和Setter方法
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getSales() {
return sales;
}
public void setSales(int sales) {
this.sales = sales;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", productId='" + productId + '\'' +
", productName='" + productName + '\'' +
", price=" + price +
", sales=" + sales +
'}';
}
}Mapper接口:
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface ProductMapper {
List<Product> findAll();
int insert(Product product);
List<Product> findBySalesGreaterThan(int sales);
}Mapper XML文件(src/main/resources/mapper/ProductMapper.xml):
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.ProductMapper">
<resultMap id="ProductResultMap" type="com.example.demo.entity.Product">
<id property="id" column="id"/>
<result property="productId" column="product_id"/>
<result property="productName" column="product_name"/>
<result property="price" column="price"/>
<result property="sales" column="sales"/>
</resultMap>
<select id="findAll" resultMap="ProductResultMap">
SELECT * FROM product
</select>
<insert id="insert" parameterType="com.example.demo.entity.Product">
INSERT INTO product (product_id, product_name, price, sales) VALUES (#{productId}, #{productName}, #{price}, #{sales})
</insert>
<select id="findBySalesGreaterThan" parameterType="int" resultMap="ProductResultMap">
SELECT * FROM product WHERE sales > #{sales}
</select>
</mapper>控制器類(lèi):
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductMapper productMapper;
@GetMapping("/")
public List<Product> getAllProducts() {
return productMapper.findAll();
}
@PostMapping("/")
public int addProduct(@RequestBody Product product) {
return productMapper.insert(product);
}
@GetMapping("/top-selling")
public List<Product> getTopSellingProducts(@RequestParam int topN) {
List<Product> products = productMapper.findBySalesGreaterThan(0);
products.sort((p1, p2) -> p2.getSales() - p1.getSales());
if (products.size() > topN) {
return products.subList(0, topN);
}
return products;
}
}測(cè)試類(lèi):
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest
class ProductApplicationTests {
@Autowired
private ProductController productController;
@Test
void contextLoads() {
}
@Test
void testGetAllProducts() {
List<Product> products = productController.getAllProducts();
assertEquals(5, products.size());
}
@Test
void testAddProduct() {
Product product = new Product("P006", "平板", 2000.0, 70);
int count = productController.addProduct(product);
assertEquals(1, count);
}
@Test
void testGetTopSellingProducts() {
List<Product> topSellingProducts = productController.getTopSellingProducts(3);
assertEquals(3, topSellingProducts.size());
assertEquals("P004", topSellingProducts.get(0).getProductId());
assertEquals("P005", topSellingProducts.get(1).getProductId());
assertEquals("P001", topSellingProducts.get(2).getProductId());
}
}? 結(jié)論:集成MyBatis的步驟包括添加MyBatis依賴(lài)、配置MyBatis連接信息、創(chuàng)建實(shí)體類(lèi)、創(chuàng)建Mapper接口、創(chuàng)建Mapper XML文件、創(chuàng)建控制器類(lèi)、測(cè)試應(yīng)用。
18.6 Spring Boot與JPA的集成
Spring Boot與JPA的集成是常用的數(shù)據(jù)訪問(wèn)方法之一。
18.6.1 集成JPA的步驟
定義:集成JPA的步驟是指使用Spring Boot與JPA集成的方法。
步驟:
- 在pom.xml文件中添加JPA依賴(lài)。
- 在application.properties或application.yml文件中配置JPA連接信息。
- 創(chuàng)建實(shí)體類(lèi)。
- 創(chuàng)建Repository接口。
- 創(chuàng)建控制器類(lèi)。
- 測(cè)試應(yīng)用。
示例:
pom.xml文件中的JPA依賴(lài):
<dependencies>
<!-- Web依賴(lài) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Data JPA依賴(lài) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL依賴(lài) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 測(cè)試依賴(lài) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>application.properties文件中的JPA連接信息:
# 服務(wù)器端口 server.port=8080 # 數(shù)據(jù)庫(kù)連接信息 spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=root spring.datasource.password=123456 # JPA配置 spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
實(shí)體類(lèi)、Repository接口、控制器類(lèi)、測(cè)試類(lèi)與集成MySQL的示例相同。
? 結(jié)論:集成JPA的步驟包括添加JPA依賴(lài)、配置JPA連接信息、創(chuàng)建實(shí)體類(lèi)、創(chuàng)建Repository接口、創(chuàng)建控制器類(lèi)、測(cè)試應(yīng)用。
18.7 Spring Boot的事務(wù)管理
Spring Boot的事務(wù)管理是數(shù)據(jù)訪問(wèn)的重要組件。
18.7.1 事務(wù)管理的定義
定義:事務(wù)管理是指使用Spring Boot進(jìn)行事務(wù)處理的方法。
作用:
- 保證數(shù)據(jù)的一致性。
- 保證數(shù)據(jù)的完整性。
- 保證數(shù)據(jù)的原子性。
常用注解:
- @Transactional:標(biāo)記方法或類(lèi)為事務(wù)方法。
示例:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Transactional
public void addProduct(Product product) {
productRepository.save(product);
}
@Transactional
public void updateProduct(Product product) {
productRepository.save(product);
}
@Transactional
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
@Transactional(readOnly = true)
public List<Product> getAllProducts() {
return productRepository.findAll();
}
@Transactional(readOnly = true)
public List<Product> getTopSellingProducts(int topN) {
List<Product> products = productRepository.findBySalesGreaterThan(0);
products.sort((p1, p2) -> p2.getSales() - p1.getSales());
if (products.size() > topN) {
return products.subList(0, topN);
}
return products;
}
}? 結(jié)論:事務(wù)管理是指使用Spring Boot進(jìn)行事務(wù)處理的方法,常用注解包括@Transactional。
18.8 Spring Boot的實(shí)際應(yīng)用場(chǎng)景
在實(shí)際開(kāi)發(fā)中,Spring Boot數(shù)據(jù)訪問(wèn)與數(shù)據(jù)庫(kù)集成的應(yīng)用場(chǎng)景非常廣泛,如:
- 實(shí)現(xiàn)商品的展示與購(gòu)買(mǎi)。
- 實(shí)現(xiàn)訂單的管理。
- 實(shí)現(xiàn)用戶(hù)的管理。
- 實(shí)現(xiàn)博客的發(fā)布與管理。
示例:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.persistence.*;
import java.util.List;
// 產(chǎn)品類(lèi)
@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String productId;
private String productName;
private double price;
private int sales;
public Product() {
}
public Product(String productId, String productName, double price, int sales) {
this.productId = productId;
this.productName = productName;
this.price = price;
this.sales = sales;
}
// Getter和Setter方法
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getSales() {
return sales;
}
public void setSales(int sales) {
this.sales = sales;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", productId='" + productId + '\'' +
", productName='" + productName + '\'' +
", price=" + price +
", sales=" + sales +
'}';
}
}
// 產(chǎn)品Repository
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findBySalesGreaterThan(int sales);
}
// 產(chǎn)品Service
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Transactional
public void addProduct(Product product) {
productRepository.save(product);
}
@Transactional
public void updateProduct(Product product) {
productRepository.save(product);
}
@Transactional
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
@Transactional(readOnly = true)
public List<Product> getAllProducts() {
return productRepository.findAll();
}
@Transactional(readOnly = true)
public List<Product> getTopSellingProducts(int topN) {
List<Product> products = productRepository.findBySalesGreaterThan(0);
products.sort((p1, p2) -> p2.getSales() - p1.getSales());
if (products.size() > topN) {
return products.subList(0, topN);
}
return products;
}
}
// 產(chǎn)品控制器
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/")
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
@PostMapping("/")
public void addProduct(@RequestBody Product product) {
productService.addProduct(product);
}
@PutMapping("/{id}")
public void updateProduct(@PathVariable Long id, @RequestBody Product product) {
product.setId(id);
productService.updateProduct(product);
}
@DeleteMapping("/{id}")
public void deleteProduct(@PathVariable Long id) {
productService.deleteProduct(id);
}
@GetMapping("/top-selling")
public List<Product> getTopSellingProducts(@RequestParam int topN) {
return productService.getTopSellingProducts(topN);
}
}
// 應(yīng)用啟動(dòng)類(lèi)
@SpringBootApplication
public class ProductApplication {
public static void main(String[] args) {
SpringApplication.run(ProductApplication.class, args);
}
@Autowired
private ProductService productService;
public void run(String... args) {
// 初始化數(shù)據(jù)
productService.addProduct(new Product("P001", "手機(jī)", 1000.0, 100));
productService.addProduct(new Product("P002", "電腦", 5000.0, 50));
productService.addProduct(new Product("P003", "電視", 3000.0, 80));
productService.addProduct(new Product("P004", "手表", 500.0, 200));
productService.addProduct(new Product("P005", "耳機(jī)", 300.0, 150));
}
}
// 測(cè)試類(lèi)
@SpringBootTest
class ProductApplicationTests {
@Autowired
private ProductController productController;
@Test
void contextLoads() {
}
@Test
void testGetAllProducts() {
List<Product> products = productController.getAllProducts();
assertEquals(5, products.size());
}
@Test
void testAddProduct() {
Product product = new Product("P006", "平板", 2000.0, 70);
productController.addProduct(product);
List<Product> products = productController.getAllProducts();
assertEquals(6, products.size());
}
@Test
void testUpdateProduct() {
Product product = new Product("P001", "手機(jī)", 1500.0, 120);
productController.updateProduct(1L, product);
List<Product> products = productController.getAllProducts();
assertEquals(1500.0, products.get(0).getPrice());
}
@Test
void testDeleteProduct() {
productController.deleteProduct(2L);
List<Product> products = productController.getAllProducts();
assertEquals(4, products.size());
}
@Test
void testGetTopSellingProducts() {
List<Product> topSellingProducts = productController.getTopSellingProducts(3);
assertEquals(3, topSellingProducts.size());
assertEquals("P004", topSellingProducts.get(0).getProductId());
assertEquals("P005", topSellingProducts.get(1).getProductId());
assertEquals("P001", topSellingProducts.get(2).getProductId());
}
}輸出結(jié)果:
- 訪問(wèn)http://localhost:8080/api/products/:
[{"id":1,"productId":"P001","productName":"手機(jī)","price":1500.0,"sales":120},{"id":3,"productId":"P003","productName":"電視","price":3000.0,"sales":80},{"id":4,"productId":"P004","productName":"手表","price":500.0,"sales":200},{"id":5,"productId":"P005","productName":"耳機(jī)","price":300.0,"sales":150},{"id":6,"productId":"P006","productName":"平板","price":2000.0,"sales":70}] - 訪問(wèn)http://localhost:8080/api/products/top-selling?topN=3:
[{"id":4,"productId":"P004","productName":"手表","price":500.0,"sales":200},{"id":5,"productId":"P005","productName":"耳機(jī)","price":300.0,"sales":150},{"id":1,"productId":"P001","productName":"手機(jī)","price":1500.0,"sales":120}]
? 結(jié)論:在實(shí)際開(kāi)發(fā)中,Spring Boot數(shù)據(jù)訪問(wèn)與數(shù)據(jù)庫(kù)集成的應(yīng)用場(chǎng)景非常廣泛,需要根據(jù)實(shí)際問(wèn)題選擇合適的數(shù)據(jù)訪問(wèn)方法。
總結(jié)
本章我們學(xué)習(xí)了Spring Boot數(shù)據(jù)訪問(wèn)與數(shù)據(jù)庫(kù)集成,包括Spring Boot數(shù)據(jù)訪問(wèn)的基本方法、Spring Boot與MySQL的集成、Spring Boot與H2的集成、Spring Boot與MyBatis的集成、Spring Boot與JPA的集成、Spring Boot的事務(wù)管理、Spring Boot的實(shí)際應(yīng)用場(chǎng)景,學(xué)會(huì)了在實(shí)際開(kāi)發(fā)中處理數(shù)據(jù)庫(kù)訪問(wèn)問(wèn)題。其中,Spring Boot數(shù)據(jù)訪問(wèn)的基本方法、Spring Boot與MySQL的集成、Spring Boot與H2的集成、Spring Boot與MyBatis的集成、Spring Boot與JPA的集成、Spring Boot的事務(wù)管理、Spring Boot的實(shí)際應(yīng)用場(chǎng)景是本章的重點(diǎn)內(nèi)容。從下一章開(kāi)始,我們將學(xué)習(xí)Spring Boot的其他組件、微服務(wù)等內(nèi)容。
到此這篇關(guān)于Spring Boot 數(shù)據(jù)訪問(wèn)與數(shù)據(jù)庫(kù)集成的文章就介紹到這了,更多相關(guān)springboot數(shù)據(jù)訪問(wèn)和數(shù)據(jù)庫(kù)集成內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot數(shù)據(jù)訪問(wèn)的實(shí)現(xiàn)
- SpringBoot對(duì)數(shù)據(jù)訪問(wèn)層進(jìn)行單元測(cè)試的方法詳解
- 深入了解Springboot核心知識(shí)點(diǎn)之?dāng)?shù)據(jù)訪問(wèn)配置
- SpringBoot中Mybatis + Druid 數(shù)據(jù)訪問(wèn)的詳細(xì)過(guò)程
- SpringBoot數(shù)據(jù)訪問(wèn)自定義使用Druid數(shù)據(jù)源的方法
- SpringBoot+MyBatis簡(jiǎn)單數(shù)據(jù)訪問(wèn)應(yīng)用的實(shí)例代碼
相關(guān)文章
解決Sentinel鏈路模式規(guī)則無(wú)效問(wèn)題
本文介紹了如何在Spring Cloud Alibaba項(xiàng)目中使用Sentinel鏈路流控規(guī)則,并解決規(guī)則不生效的問(wèn)題,通過(guò)關(guān)閉Sentinel過(guò)濾器,可以避免重復(fù)統(tǒng)計(jì)請(qǐng)求2025-01-01
Servlet實(shí)現(xiàn)簡(jiǎn)單文件上傳功能
這篇文章主要為大家詳細(xì)介紹了Servlet實(shí)現(xiàn)簡(jiǎn)單文件上傳功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10
SpringBoot文件上傳功能的實(shí)現(xiàn)方法
這篇文章主要介紹了SpringBoot文件上傳功能的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
分析Java并發(fā)編程之信號(hào)量Semaphore
Semaphore一般譯作信號(hào)量,它也是一種線程同步工具,主要用于多個(gè)線程對(duì)共享資源進(jìn)行并行操作的一種工具類(lèi)。它代表了一種許可的概念,是否允許多線程對(duì)同一資源進(jìn)行操作的許可,使用Semaphore可以控制并發(fā)訪問(wèn)資源的線程個(gè)數(shù)2021-06-06
微信公眾號(hào)模板消息接口開(kāi)發(fā)Java實(shí)現(xiàn)方法代碼
這篇文章主要介紹了微信公眾號(hào)模板消息接口開(kāi)發(fā)Java實(shí)現(xiàn)的相關(guān)資料,,該接口可以用于向關(guān)注公眾號(hào)的用戶(hù)推送消息,包括群發(fā)和指定用戶(hù)發(fā)送消息,文章詳細(xì)介紹了如何獲取公眾號(hào)的測(cè)試信息、配置接口信息和獲取access_token,需要的朋友可以參考下2024-12-12
Maven項(xiàng)目web多圖片上傳及格式驗(yàn)證的實(shí)現(xiàn)
本文主要介紹了Maven項(xiàng)目web多圖片上傳及格式驗(yàn)證的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10
Java分頁(yè)查詢(xún)--分頁(yè)顯示(實(shí)例講解)
下面小編就為大家?guī)?lái)一篇Java分頁(yè)查詢(xún)--分頁(yè)顯示(實(shí)例講解)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08
一文吃透消息隊(duì)列RocketMQ實(shí)現(xiàn)消費(fèi)冪等原理
這篇文章主要介紹了消息隊(duì)列RocketMQ實(shí)現(xiàn)消費(fèi)冪等的全面講解,幫助大家吃透RocketMQ消息隊(duì)列消費(fèi)冪等,更好的的應(yīng)用與工作實(shí)踐,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01

