跳到主要内容
Spring Boot 数据访问与数据库集成实战 | 极客日志
Java java
Spring Boot 数据访问与数据库集成实战 Spring Boot 数据访问涵盖多种持久化方案,包括 JDBC、JPA 及 MyBatis。通过 Starter 自动配置简化了 MySQL、H2 等数据库的集成流程。文章详细展示了实体类定义、Repository 接口编写、Mapper XML 映射以及事务注解的使用,并结合实际商品管理场景演示了完整的数据交互链路,帮助开发者快速掌握企业级应用中的数据层构建方法。
Spring Boot 数据访问与数据库集成
核心概念与组件
Spring Boot 的数据访问功能旨在简化数据库操作,让开发者能专注于业务逻辑而非底层连接管理。其核心价值在于实现数据的增删改查、事务控制以及持久化存储。
常用的数据访问组件包括:
JdbcTemplate :适合需要精细控制 JDBC 操作的场景。
JPA (Java Persistence API) :通过 ORM 映射对象与关系表,减少 SQL 编写。
MyBatis :提供灵活的 SQL 映射,适合复杂查询。
Hibernate :作为 JPA 的流行实现,提供完整的 ORM 支持。
与 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
runtime
org.springframework.boot
spring-boot-starter-test
test
</artifactId >
<scope >
</scope >
</dependency >
<dependency >
<groupId >
</groupId >
<artifactId >
</artifactId >
<scope >
</scope >
</dependency >
</dependencies >
在 application.properties 中配置连接信息:
# 服务器端口
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
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;
@Override
public String toString () {
return "Product{" +
"id=" + id +
", productId='" + productId + '\'' +
", productName='" + productName + '\'' +
", price=" + price +
", sales=" + sales +
'}' ;
}
}
3. 数据访问层 创建 Repository 接口继承 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) ;
}
4. 控制器与服务 结合 Spring MVC 暴露 RESTful 接口:
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 内存数据库非常适合开发和单元测试阶段,无需安装外部服务。
配置差异 只需替换 pom.xml 中的数据库依赖为 H2,并修改配置文件:
<dependency >
<groupId > com.h2database</groupId >
<artifactId > h2</artifactId >
<scope > runtime</scope >
</dependency >
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
# 开启 H2 控制台便于调试
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
实体类与 Repository 接口通常无需改动,因为 JPA 会自动根据 DDL 策略生成表结构。
与 MyBatis 集成 对于需要手写 SQL 或处理复杂关联查询的场景,MyBatis 提供了更灵活的控制。
依赖与配置 <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
Mapper 接口与 XML 定义 Mapper 接口,并在 XML 文件中编写 SQL:
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 可优化只读查询的性能。若方法抛出未捕获的运行时异常,默认会回滚事务。
实际应用场景 综合上述技术点,我们可以构建一个完整的产品管理系统。启动应用后,初始化数据并调用接口验证:
访问 http://localhost:8080/api/products/top-selling?topN=3 获取销量前三的商品:
[
{ "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 在处理典型业务数据时的便捷性。根据具体项目需求(如查询复杂度、性能要求),选择合适的持久化方案是关键。
相关免费在线工具 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