跳到主要内容
Spring Boot 数据访问与数据库集成详解 | 极客日志
Java java
Spring Boot 数据访问与数据库集成详解 Spring Boot 数据访问涵盖 MySQL、H2、MyBatis 及 JPA 集成方案。通过配置依赖与连接信息,结合实体类、Repository 或 Mapper 接口实现持久化操作。事务管理利用@Transactional 注解保障数据一致性。实际场景涉及商品展示、订单管理等 CRUD 功能,需根据项目需求选择合适的数据访问层技术栈。
芝士奶盖 发布于 2026/3/22 更新于 2026/5/4 6 浏览Spring Boot 数据访问与数据库集成
在 Spring Boot 应用中,数据访问层(Persistence Layer)是连接业务逻辑与持久化存储的关键。掌握不同数据库的集成方式、ORM 框架的选择以及事务管理策略,是构建稳定后端服务的基础。
核心组件概览
Spring Boot 提供了多种数据访问方案,开发者可根据项目复杂度灵活选择:
JdbcTemplate :适合轻量级 JDBC 操作,控制粒度细。
JPA (Hibernate) :面向对象映射标准,开发效率高,适合复杂关系模型。
MyBatis :SQL 可控性强,适合对性能有极致要求的场景。
H2 :内存数据库,常用于开发测试环境。
与 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 >
<dependency >
<groupId > mysql</groupId >
<artifactId > mysql-connector-java</artifactId >
<scope > runtime
org.springframework.boot
spring-boot-starter-test
test
</scope >
</dependency >
<dependency >
<groupId >
</groupId >
<artifactId >
</artifactId >
<scope >
</scope >
</dependency >
</dependencies >
在 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
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
2. 实体与仓库 定义实体类时,使用 JPA 注解映射表结构。注意字段类型与 Java 类型的对应关系。
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;
}
@Override
public String toString () {
return "Product{" +
"id=" + id +
", productId='" + productId + '\'' +
", productName='" + productName + '\'' +
", price=" + price +
", sales=" + sales +
'}' ;
}
}
通过继承 JpaRepository 快速获得 CRUD 能力,并可自定义查询方法:
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) ;
}
3. 控制器与服务 Controller 层负责暴露 REST API,Service 层处理业务逻辑与事务。这里为了演示简洁,将 Service 逻辑直接放在 Controller 或简化 Service 调用中。
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
实体类与 Repository 接口可复用 MySQL 部分的代码,无需修改逻辑,仅改变底层存储实现。
灵活映射:MyBatis 集成 当需要精细控制 SQL 语句或处理复杂查询时,MyBatis 是更好的选择。它通过 XML 或注解将 Java 对象与 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 接口,并在 XML 文件中编写 SQL。这种方式让 SQL 与 Java 代码解耦,便于维护。
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 可优化只读查询的性能。同时,确保 Service 方法被 Spring 容器管理(如 @Service),否则事务可能失效。
综合应用场景 实际项目中,通常结合上述技术栈构建完整功能。例如商品管理系统,需支持展示、购买、订单关联等。
@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,即可获取销量前三的商品列表。这种分层架构不仅清晰,也便于后续扩展微服务或更换数据库。
总结 本章涵盖了 Spring Boot 数据访问的核心实践。从基础的 MySQL 集成到 H2 测试环境,再到 MyBatis 的灵活 SQL 控制,以及事务管理的兜底机制,构成了完整的数据持久化方案。在实际开发中,建议优先使用 JPA 提升开发效率,仅在遇到性能瓶颈或复杂 SQL 需求时引入 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