跳到主要内容
Spring Boot 数据访问与数据库集成实战 | 极客日志
Java java
Spring Boot 数据访问与数据库集成实战 Spring Boot 通过自动配置大幅简化了数据库连接与操作,支持 JPA、MyBatis 及 JDBC 等多种持久化方案。内容涵盖 MySQL 与 H2 的配置差异、实体映射、Repository 设计以及事务管理注解的使用,并结合商品管理场景演示完整的数据访问链路,助力开发者快速落地生产级应用。
Pythonist 发布于 2026/3/29 0 浏览Spring Boot 数据访问与数据库集成
在构建企业级应用时,数据持久化往往是核心环节。Spring Boot 通过自动配置机制,极大地简化了数据库集成的复杂度。无论是传统的 JDBC、流行的 JPA,还是灵活的 MyBatis,Spring Boot 都能提供开箱即用的支持。
数据访问概述
Spring Boot 的数据访问层旨在屏蔽底层数据库的差异,让开发者专注于业务逻辑。常用的组件包括:
JdbcTemplate :适合需要精细控制 SQL 的场景,基于 JDBC 封装。
JPA (Hibernate) :对象关系映射标准,通过注解或 XML 定义实体,自动生成 SQL。
MyBatis :半自动化 ORM,SQL 可控性强,适合复杂查询。
Hibernate :JPA 的具体实现之一,功能强大。
集成 MySQL
MySQL 是生产环境中最常见的选择。集成过程主要涉及依赖引入、配置连接及实体映射。
1. 添加依赖
在 pom.xml 中引入 Web、Data JPA 和 MySQL 驱动:
<dependencies >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-web</artifactId >
</dependency >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-data-jpa</artifactId >
</dependency >
< >
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
dependency
<groupId >
</groupId >
<artifactId >
</artifactId >
<scope >
</scope >
</dependency >
<dependency >
<groupId >
</groupId >
<artifactId >
</artifactId >
<scope >
</scope >
</dependency >
</dependencies >
2. 配置文件 在 application.properties 中指定数据源和 JPA 行为:
# 服务器端口
server.port=8080
# 数据库连接信息
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
3. 实体与 Repository 使用 JPA 注解定义实体类,并继承 JpaRepository 获取基础 CRUD 能力:
import javax.persistence.*;
import java.util.List;
@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 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; }
}
@Repository
public interface ProductRepository extends JpaRepository <Product, Long> {
List<Product> findBySalesGreaterThan (int sales) ;
}
4. 控制器与测试 结合 @RestController 暴露 API,并通过单元测试验证逻辑:
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;
}
}
集成 H2 数据库 H2 内存数据库非常适合开发和测试阶段,无需安装额外服务。配置上只需替换驱动 URL 和启动控制台即可:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
其余代码结构与 MySQL 集成基本一致,这使得切换数据库变得异常简单。
集成 MyBatis 当需要更复杂的 SQL 控制时,MyBatis 是更好的选择。相比 JPA 的约定优于配置,MyBatis 允许手写 SQL,灵活性更高。
1. 依赖与配置 <dependency >
<groupId > org.mybatis.spring.boot</groupId >
<artifactId > mybatis-spring-boot-starter</artifactId >
<version > 2.3.0</version >
</dependency >
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.demo.entity
2. Mapper 接口与 XML 定义接口并使用 @Mapper 注解,SQL 语句写在 XML 文件中:
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) ;
}
<?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 >
事务管理 在数据访问层,保证数据的一致性至关重要。Spring Boot 通过 @Transactional 注解轻松实现声明式事务。
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Transactional
public void addProduct (Product product) {
productRepository.save(product);
}
@Transactional(readOnly = true)
public List<Product> getAllProducts () {
return productRepository.findAll();
}
}
注意:readOnly = true 可以优化只读查询的性能。若方法抛出运行时异常,默认会回滚;受检异常则不会,需根据需求调整配置。
实际应用场景 将上述组件组合,可构建完整的商品管理系统。以下是一个整合后的示例,展示了从启动初始化到 API 调用的完整流程:
@SpringBootApplication
public class ProductApplication {
public static void main (String[] args) {
SpringApplication.run(ProductApplication.class, args);
}
@Autowired
private ProductService productService;
public void run (String... args) {
productService.addProduct(new Product ("P001" , "手机" , 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" , "耳机" , 300.0 , 150 ));
}
}
调用 /api/products/top-selling?topN=3 接口,返回销量最高的前三件商品,JSON 响应如下:
[
{ "id" : 4 , "productId" : "P004" , "productName" : "手表" , "price" : 500.0 , "sales" : 200 } ,
{ "id" : 5 , "productId" : "P005" , "productName" : "耳机" , "price" : 300.0 , "sales" : 150 } ,
{ "id" : 1 , "productId" : "P001" , "productName" : "手机" , "price" : 1500.0 , "sales" : 120 }
]
总结 Spring Boot 提供了丰富的数据访问方案,开发者可根据项目规模与复杂度灵活选择。JPA 适合快速开发,MyBatis 适合复杂查询,而事务管理则是保障数据安全的基石。掌握这些核心技能,就能从容应对各种数据库集成挑战。
相关免费在线工具 Keycode 信息 查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
Escape 与 Native 编解码 JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
JavaScript / HTML 格式化 使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
JavaScript 压缩与混淆 Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
Base64 字符串编码/解码 将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
Base64 文件转换器 将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online