百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

Spring Boot JDBC 与 JdbcTemplate 全面指南(万字保姆级教程)

ztj100 2025-05-28 21:44 7 浏览 0 评论

一、Spring Boot JDBC 基础

1.1 JDBC 简介与演进

JDBC (Java Database Connectivity) 是 Java 语言中用来规范客户端程序如何访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。它属于 Java 标准版的一部分,由 java.sqljavax.sql 包组成。

传统 JDBC 开发流程:

  1. 加载数据库驱动
  2. 建立数据库连接
  3. 创建 Statement 对象
  4. 执行 SQL 语句
  5. 处理结果集
  6. 关闭连接

传统 JDBC 的主要问题:

  • 大量样板代码
  • 需要手动管理资源
  • 异常处理繁琐
  • 缺乏抽象层
// 传统JDBC示例
public class TraditionalJdbcExample {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // 1. 加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2. 获取连接
            conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/test", "root", "password");
            // 3. 创建statement
            stmt = conn.createStatement();
            // 4. 执行查询
            rs = stmt.executeQuery("SELECT id, name FROM users");
            // 5. 处理结果
            while (rs.next()) {
                System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6. 关闭资源
            try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
            try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
            try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
        }
    }
}

1.2 Spring Boot 中的 JDBC 支持

Spring Boot 通过自动配置简化了 JDBC 的使用,主要提供了以下功能:

  • 自动配置数据源
  • 自动配置 JdbcTemplate
  • 简化事务管理
  • 提供多种数据库支持

Spring Boot JDBC 的核心优势:

  1. 简化配置:通过 application.propertiesapplication.yml 文件配置数据源
  2. 自动管理资源:无需手动关闭连接
  3. 统一的异常体系:将检查异常转换为运行时异常
  4. 模板方法模式:JdbcTemplate 封装了常用操作

1.3 Spring Boot JDBC 自动配置原理

Spring Boot 的 JDBC 自动配置主要通过
DataSourceAutoConfiguration

JdbcTemplateAutoConfiguration
实现:

自动配置的关键点:

  1. 根据 classpath 中的驱动类自动检测数据库类型
  2. 根据配置属性创建 DataSource 实例
  3. 自动配置 JdbcTemplate 和 NamedParameterJdbcTemplate
  4. 自动配置事务管理器

二、JdbcTemplate 核心功能

2.1 JdbcTemplate 基础使用

JdbcTemplate 是 Spring JDBC 核心包中的核心类,它简化了 JDBC 的使用,处理了资源的创建和释放,帮助我们避免常见的错误。

基本配置示例:

@Configuration
public class JdbcTemplateConfig {
    
    @Bean
    public DataSource dataSource() {
        // 使用HikariCP连接池
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("password");
        dataSource.setMaximumPoolSize(10);
        return dataSource;
    }
    
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

基础 CRUD 操作示例:

@Repository
public class UserRepository {
    
    private final JdbcTemplate jdbcTemplate;
    
    public UserRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    // 插入数据
    public int insert(User user) {
        String sql = "INSERT INTO users (name, email, age) VALUES (?, ?, ?)";
        return jdbcTemplate.update(sql, user.getName(), user.getEmail(), user.getAge());
    }
    
    // 查询单个对象
    public User findById(Long id) {
        String sql = "SELECT * FROM users WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, (rs, rowNum) -> {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setName(rs.getString("name"));
            user.setEmail(rs.getString("email"));
            user.setAge(rs.getInt("age"));
            return user;
        });
    }
    
    // 查询列表
    public List<User> findAll() {
        String sql = "SELECT * FROM users";
        return jdbcTemplate.query(sql, (rs, rowNum) -> {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setName(rs.getString("name"));
            user.setEmail(rs.getString("email"));
            user.setAge(rs.getInt("age"));
            return user;
        });
    }
    
    // 更新数据
    public int update(User user) {
        String sql = "UPDATE users SET name = ?, email = ?, age = ? WHERE id = ?";
        return jdbcTemplate.update(sql, user.getName(), user.getEmail(), user.getAge(), user.getId());
    }
    
    // 删除数据
    public int delete(Long id) {
        String sql = "DELETE FROM users WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }
}

2.2 JdbcTemplate 核心方法解析

JdbcTemplate 提供了丰富的方法来执行各种数据库操作,主要可以分为以下几类:

方法类别

主要方法

说明

更新操作

update(), batchUpdate()

执行 INSERT, UPDATE, DELETE 等 DML 语句

查询操作

query(), queryForObject(), queryForList(), queryForMap()

执行 SELECT 查询并返回结果

执行操作

execute()

执行任意 SQL 语句,包括 DDL

存储过程

call()

调用存储过程

批处理

batchUpdate()

执行批量操作

方法详细说明:

  1. update() 方法
  2. 用于执行 INSERT、UPDATE、DELETE 等 DML 语句
  3. 返回受影响的行数
  4. 有多个重载版本,支持 PreparedStatement 和批量操作
// 基本update示例
public int updateUserName(Long id, String newName) {
    String sql = "UPDATE users SET name = ? WHERE id = ?";
    return jdbcTemplate.update(sql, newName, id);
}

// 使用PreparedStatementCreator
public int updateUser(User user) {
    return jdbcTemplate.update(con -> {
        PreparedStatement ps = con.prepareStatement(
            "UPDATE users SET name = ?, email = ? WHERE id = ?");
        ps.setString(1, user.getName());
        ps.setString(2, user.getEmail());
        ps.setLong(3, user.getId());
        return ps;
    });
}
  1. query() 方法
  2. 用于执行查询并处理结果集
  3. 需要提供 RowMapper 或 ResultSetExtractor
  4. 返回对象列表或单个对象
// 查询列表
public List<User> findUsersByAgeGreaterThan(int age) {
    String sql = "SELECT * FROM users WHERE age > ?";
    return jdbcTemplate.query(sql, new Object[]{age}, (rs, rowNum) -> {
        User user = new User();
        user.setId(rs.getLong("id"));
        user.setName(rs.getString("name"));
        user.setEmail(rs.getString("email"));
        user.setAge(rs.getInt("age"));
        return user;
    });
}

// 查询单个值
public int countUsers() {
    String sql = "SELECT COUNT(*) FROM users";
    return jdbcTemplate.queryForObject(sql, Integer.class);
}
  1. batchUpdate() 方法
  2. 用于执行批量操作
  3. 比单独执行多个语句更高效
  4. 返回每行操作影响的行数数组
// 批量插入
public int[] batchInsert(List<User> users) {
    String sql = "INSERT INTO users (name, email, age) VALUES (?, ?, ?)";
    return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            User user = users.get(i);
            ps.setString(1, user.getName());
            ps.setString(2, user.getEmail());
            ps.setInt(3, user.getAge());
        }
        
        @Override
        public int getBatchSize() {
            return users.size();
        }
    });
}

2.3 结果集处理策略

JdbcTemplate 提供了多种结果集处理方式:

  1. RowMapper
  2. 将结果集的每一行映射为一个对象
  3. 常用于查询返回多个对象的场景
public class UserRowMapper implements RowMapper<User> {
    @Override
    public User mapRow(ResultSet rs, int rowNum) throws SQLException {
        User user = new User();
        user.setId(rs.getLong("id"));
        user.setName(rs.getString("name"));
        user.setEmail(rs.getString("email"));
        user.setAge(rs.getInt("age"));
        return user;
    }
}

// 使用自定义RowMapper
public List<User> findAll() {
    String sql = "SELECT * FROM users";
    return jdbcTemplate.query(sql, new UserRowMapper());
}
  1. ResultSetExtractor
  2. 对整个结果集进行处理
  3. 适合复杂的结果集映射场景
public Map<Long, User> findAllAsMap() {
    String sql = "SELECT * FROM users";
    return jdbcTemplate.query(sql, rs -> {
        Map<Long, User> userMap = new HashMap<>();
        while (rs.next()) {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setName(rs.getString("name"));
            user.setEmail(rs.getString("email"));
            user.setAge(rs.getInt("age"));
            userMap.put(user.getId(), user);
        }
        return userMap;
    });
}
  1. RowCallbackHandler
  2. 逐行处理结果集,不返回任何值
  3. 适合大数据量处理
public void processAllUsers() {
    String sql = "SELECT * FROM users";
    jdbcTemplate.query(sql, rs -> {
        while (rs.next()) {
            // 处理每一行数据
            System.out.println("Processing user: " + rs.getString("name"));
        }
    });
}

三、高级特性与最佳实践

3.1 命名参数 JdbcTemplate


NamedParameterJdbcTemplate 是 JdbcTemplate 的扩展,支持使用命名参数而不是传统的占位符(?)。

优势:

  • 更清晰的 SQL 语句
  • 参数顺序无关
  • 支持 Map 和对象作为参数源

基本使用:

@Repository
public class NamedParamUserRepository {
    
    private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    
    public NamedParamUserRepository(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
    }
    
    // 使用Map作为参数源
    public int insert(User user) {
        String sql = "INSERT INTO users (name, email, age) VALUES (:name, :email, :age)";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", user.getName());
        paramMap.put("email", user.getEmail());
        paramMap.put("age", user.getAge());
        return namedParameterJdbcTemplate.update(sql, paramMap);
    }
    
    // 使用对象作为参数源
    public int update(User user) {
        String sql = "UPDATE users SET name = :name, email = :email, age = :age WHERE id = :id";
        SqlParameterSource paramSource = new BeanPropertySqlParameterSource(user);
        return namedParameterJdbcTemplate.update(sql, paramSource);
    }
    
    // 查询示例
    public User findById(Long id) {
        String sql = "SELECT * FROM users WHERE id = :id";
        return namedParameterJdbcTemplate.queryForObject(
            sql, 
            Collections.singletonMap("id", id),
            (rs, rowNum) -> {
                User user = new User();
                user.setId(rs.getLong("id"));
                user.setName(rs.getString("name"));
                user.setEmail(rs.getString("email"));
                user.setAge(rs.getInt("age"));
                return user;
            });
    }
}

3.2 事务管理

Spring 提供了强大的声明式事务管理支持,可以与 JdbcTemplate 完美配合使用。

编程式事务:

@Service
public class UserService {
    
    private final JdbcTemplate jdbcTemplate;
    private final TransactionTemplate transactionTemplate;
    
    public UserService(JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager) {
        this.jdbcTemplate = jdbcTemplate;
        this.transactionTemplate = new TransactionTemplate(transactionManager);
    }
    
    public void transferMoney(Long fromId, Long toId, BigDecimal amount) {
        transactionTemplate.execute(status -> {
            try {
                // 扣款
                String deductSql = "UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?";
                int rows = jdbcTemplate.update(deductSql, amount, fromId, amount);
                if (rows == 0) {
                    status.setRollbackOnly();
                    throw new InsufficientBalanceException("Insufficient balance");
                }
                
                // 存款
                String addSql = "UPDATE accounts SET balance = balance + ? WHERE id = ?";
                jdbcTemplate.update(addSql, amount, toId);
                
                return null;
            } catch (Exception e) {
                status.setRollbackOnly();
                throw e;
            }
        });
    }
}

声明式事务:

@Service
public class UserService {
    
    private final JdbcTemplate jdbcTemplate;
    
    public UserService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    @Transactional
    public void transferMoney(Long fromId, Long toId, BigDecimal amount) {
        // 扣款
        String deductSql = "UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?";
        int rows = jdbcTemplate.update(deductSql, amount, fromId, amount);
        if (rows == 0) {
            throw new InsufficientBalanceException("Insufficient balance");
        }
        
        // 存款
        String addSql = "UPDATE accounts SET balance = balance + ? WHERE id = ?";
        jdbcTemplate.update(addSql, amount, toId);
    }
    
    @Transactional(readOnly = true)
    public BigDecimal getBalance(Long accountId) {
        String sql = "SELECT balance FROM accounts WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, BigDecimal.class, accountId);
    }
}

事务传播行为:

传播行为类型

说明

REQUIRED (默认)

如果当前没有事务,就新建一个事务;如果已经存在一个事务,就加入到这个事务中

REQUIRES_NEW

新建事务,如果当前存在事务,把当前事务挂起

SUPPORTS

支持当前事务,如果当前没有事务,就以非事务方式执行

NOT_SUPPORTED

以非事务方式执行操作,如果当前存在事务,就把当前事务挂起

MANDATORY

使用当前的事务,如果当前没有事务,就抛出异常

NEVER

以非事务方式执行,如果当前存在事务,则抛出异常

NESTED

如果当前存在事务,则在嵌套事务内执行;如果当前没有事务,则执行与 REQUIRED 类似的操作

3.3 批量操作优化

批量操作可以显著提高大量数据操作的性能,JdbcTemplate 提供了多种批量操作方式。

1. 基本批量更新:

public int[] batchInsert(List<User> users) {
    String sql = "INSERT INTO users (name, email, age) VALUES (?, ?, ?)";
    return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            User user = users.get(i);
            ps.setString(1, user.getName());
            ps.setString(2, user.getEmail());
            ps.setInt(3, user.getAge());
        }
        
        @Override
        public int getBatchSize() {
            return users.size();
        }
    });
}

2. 命名参数批量更新:

public int[] namedBatchInsert(List<User> users) {
    String sql = "INSERT INTO users (name, email, age) VALUES (:name, :email, :age)";
    SqlParameterSource[] batchArgs = users.stream()
        .map(BeanPropertySqlParameterSource::new)
        .toArray(SqlParameterSource[]::new);
    return namedParameterJdbcTemplate.batchUpdate(sql, batchArgs);
}

3. 大批量数据处理:

对于非常大的数据集,可以分批处理以避免内存问题:

public void batchInsertInChunks(List<User> users, int chunkSize) {
    String sql = "INSERT INTO users (name, email, age) VALUES (?, ?, ?)";
    
    List<User> chunk = new ArrayList<>(chunkSize);
    for (User user : users) {
        chunk.add(user);
        if (chunk.size() == chunkSize) {
            jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    User u = chunk.get(i);
                    ps.setString(1, u.getName());
                    ps.setString(2, u.getEmail());
                    ps.setInt(3, u.getAge());
                }
                
                @Override
                public int getBatchSize() {
                    return chunk.size();
                }
            });
            chunk.clear();
        }
    }
    
    // 处理剩余记录
    if (!chunk.isEmpty()) {
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                User u = chunk.get(i);
                ps.setString(1, u.getName());
                ps.setString(2, u.getEmail());
                ps.setInt(3, u.getAge());
            }
            
            @Override
            public int getBatchSize() {
                return chunk.size();
            }
        });
    }
}

3.4 存储过程调用

JdbcTemplate 支持调用数据库存储过程:

public class UserRepository {
    
    private final JdbcTemplate jdbcTemplate;
    
    public UserRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    // 调用简单存储过程
    public int getUserCount() {
        return jdbcTemplate.execute(
            (CallableStatementCreator) con -> con.prepareCall("{call GET_USER_COUNT(?)}"),
            (CallableStatementCallback<Integer>) cs -> {
                cs.registerOutParameter(1, Types.INTEGER);
                cs.execute();
                return cs.getInt(1);
            });
    }
    
    // 调用带输入输出参数的存储过程
    public User getUserWithStats(Long userId) {
        SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
            .withProcedureName("GET_USER_WITH_STATS")
            .declareParameters(
                new SqlParameter("user_id", Types.BIGINT),
                new SqlOutParameter("user_name", Types.VARCHAR),
                new SqlOutParameter("user_email", Types.VARCHAR),
                new SqlOutParameter("login_count", Types.INTEGER),
                new SqlOutParameter("last_login", Types.TIMESTAMP));
        
        Map<String, Object> inParams = new HashMap<>();
        inParams.put("user_id", userId);
        
        Map<String, Object> out = jdbcCall.execute(inParams);
        
        User user = new User();
        user.setId(userId);
        user.setName((String) out.get("user_name"));
        user.setEmail((String) out.get("user_email"));
        user.setLoginCount((Integer) out.get("login_count"));
        user.setLastLogin((Timestamp) out.get("last_login"));
        
        return user;
    }
}

四、性能优化与监控

4.1 连接池配置

Spring Boot 默认使用 HikariCP 作为连接池,合理配置连接池对性能至关重要。

常用配置参数:

参数名

说明

推荐值

spring.datasource.hikari.maximum-pool-size

连接池最大连接数

CPU核心数 * 2 + 有效磁盘数

spring.datasource.hikari.minimum-idle

连接池最小空闲连接数

同maximum-pool-size

spring.datasource.hikari.idle-timeout

连接空闲超时时间(毫秒),超时后连接被释放

60000 (1分钟)

spring.datasource.hikari.max-lifetime

连接最大存活时间(毫秒),超时后连接被释放

1800000 (30分钟)

spring.datasource.hikari.connection-timeout

获取连接超时时间(毫秒)

30000 (30秒)

spring.datasource.hikari.connection-test-query

连接测试查询

SELECT 1 (MySQL), SELECT 1 FROM DUAL (Oracle)

配置示例 (application.yml):

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: password
    driver-class-name: com.mysql.cj.jdbc.Driver
    hikari:
      maximum-pool-size: 20
      minimum-idle: 10
      idle-timeout: 60000
      max-lifetime: 1800000
      connection-timeout: 30000
      connection-test-query: SELECT 1

4.2 SQL 监控与日志

1. 开启 SQL 日志:

在 application.properties 中添加:

# 显示SQL语句
logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG
# 显示SQL参数
logging.level.org.springframework.jdbc.core.StatementCreatorUtils=TRACE

2. 使用 P6Spy 监控 SQL:

P6Spy 是一个开源的 SQL 监控框架,可以记录所有 JDBC 调用。

配置步骤:

  1. 添加依赖:
<dependency>
    <groupId>com.github.gavlyukovskiy</groupId>
    <artifactId>p6spy-spring-boot-starter</artifactId>
    <version>1.8.1</version>
</dependency>
  1. 配置 application.yml:
spring:
  datasource:
    url: jdbc:p6spy:mysql://localhost:3306/test
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver
  1. 配置 spy.properties (src/main/resources/spy.properties):
module.log=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
appender=com.p6spy.engine.spy.appender.Slf4JLogger
logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
customLogMessageFormat=%(executionTime)ms | %(category) | connection %(connectionId) | %(sqlSingleLine)

4.3 性能优化建议

  1. 合理使用批处理
  2. 对于批量插入/更新操作,使用 batchUpdate 而不是单个 update
  3. 适当设置批处理大小 (通常 100-1000 条/批)
  4. 优化查询
  5. 只查询需要的列,避免 SELECT *
  6. 使用分页查询处理大量数据
  7. 合理使用索引
  8. 连接池调优
  9. 根据系统负载调整连接池大小
  10. 设置合理的连接超时和空闲超时
  11. 事务优化
  12. 尽量缩短事务持有时间
  13. 只读查询使用 @Transactional(readOnly = true)
  14. 合理设置事务隔离级别
  15. 缓存策略
  16. 对不经常变化的数据使用缓存
  17. 考虑使用 Spring Cache 抽象

五、实战案例:电商系统用户模块

5.1 数据库设计

CREATE TABLE users (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    phone VARCHAR(20),
    status TINYINT DEFAULT 1 COMMENT '1-正常, 0-禁用',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

CREATE TABLE user_address (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT NOT NULL,
    receiver_name VARCHAR(50) NOT NULL,
    receiver_phone VARCHAR(20) NOT NULL,
    province VARCHAR(20) NOT NULL,
    city VARCHAR(20) NOT NULL,
    district VARCHAR(20) NOT NULL,
    detail_address VARCHAR(200) NOT NULL,
    is_default TINYINT DEFAULT 0 COMMENT '1-默认地址, 0-非默认',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

5.2 领域模型

// 用户实体
public class User {
    private Long id;
    private String username;
    private String password;
    private String email;
    private String phone;
    private Integer status;
    private Date createdAt;
    private Date updatedAt;
    
    // 省略getter/setter
}

// 用户地址实体
public class UserAddress {
    private Long id;
    private Long userId;
    private String receiverName;
    private String receiverPhone;
    private String province;
    private String city;
    private String district;
    private String detailAddress;
    private Integer isDefault;
    private Date createdAt;
    private Date updatedAt;
    
    // 省略getter/setter
}

5.3 数据访问层实现

UserRepository:

@Repository
public class UserRepository {
    
    private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    
    public UserRepository(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
    }
    
    // 插入用户并返回自增ID
    public Long insert(User user) {
        String sql = "INSERT INTO users (username, password, email, phone, status) " +
                     "VALUES (:username, :password, :email, :phone, :status)";
        
        KeyHolder keyHolder = new GeneratedKeyHolder();
        SqlParameterSource paramSource = new BeanPropertySqlParameterSource(user);
        
        namedParameterJdbcTemplate.update(sql, paramSource, keyHolder, new String[]{"id"});
        
        return keyHolder.getKey().longValue();
    }
    
    // 根据用户名查找用户
    public User findByUsername(String username) {
        String sql = "SELECT * FROM users WHERE username = :username";
        try {
            return namedParameterJdbcTemplate.queryForObject(
                sql,
                Collections.singletonMap("username", username),
                (rs, rowNum) -> {
                    User user = new User();
                    user.setId(rs.getLong("id"));
                    user.setUsername(rs.getString("username"));
                    user.setPassword(rs.getString("password"));
                    user.setEmail(rs.getString("email"));
                    user.setPhone(rs.getString("phone"));
                    user.setStatus(rs.getInt("status"));
                    user.setCreatedAt(rs.getTimestamp("created_at"));
                    user.setUpdatedAt(rs.getTimestamp("updated_at"));
                    return user;
                });
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }
    
    // 更新用户信息
    public int update(User user) {
        String sql = "UPDATE users SET email = :email, phone = :phone, status = :status " +
                     "WHERE id = :id";
        SqlParameterSource paramSource = new BeanPropertySqlParameterSource(user);
        return namedParameterJdbcTemplate.update(sql, paramSource);
    }
    
    // 分页查询用户
    public Page<User> findAll(int page, int size) {
        String countSql = "SELECT COUNT(*) FROM users";
        int total = namedParameterJdbcTemplate.getJdbcTemplate().queryForObject(countSql, Integer.class);
        
        String dataSql = "SELECT * FROM users ORDER BY id LIMIT :limit OFFSET :offset";
        Map<String, Object> params = new HashMap<>();
        params.put("limit", size);
        params.put("offset", (page - 1) * size);
        
        List<User> users = namedParameterJdbcTemplate.query(
            dataSql,
            params,
            (rs, rowNum) -> {
                User user = new User();
                user.setId(rs.getLong("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setPhone(rs.getString("phone"));
                user.setStatus(rs.getInt("status"));
                user.setCreatedAt(rs.getTimestamp("created_at"));
                user.setUpdatedAt(rs.getTimestamp("updated_at"));
                return user;
            });
        
        return new PageImpl<>(users, PageRequest.of(page - 1, size), total);
    }
}

UserAddressRepository:

@Repository
public class UserAddressRepository {
    
    private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    
    public UserAddressRepository(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
    }
    
    // 添加用户地址
    public Long insert(UserAddress address) {
        String sql = "INSERT INTO user_address " +
                     "(user_id, receiver_name, receiver_phone, province, city, district, detail_address, is_default) " +
                     "VALUES (:userId, :receiverName, :receiverPhone, :province, :city, :district, :detailAddress, :isDefault)";
        
        KeyHolder keyHolder = new GeneratedKeyHolder();
        SqlParameterSource paramSource = new BeanPropertySqlParameterSource(address);
        
        namedParameterJdbcTemplate.update(sql, paramSource, keyHolder, new String[]{"id"});
        
        return keyHolder.getKey().longValue();
    }
    
    // 设置默认地址
    @Transactional
    public void setDefaultAddress(Long userId, Long addressId) {
        // 先清除该用户的所有默认地址标记
        String clearSql = "UPDATE user_address SET is_default = 0 WHERE user_id = :userId";
        namedParameterJdbcTemplate.update(clearSql, Collections.singletonMap("userId", userId));
        
        // 设置指定地址为默认
        String setSql = "UPDATE user_address SET is_default = 1 WHERE id = :id AND user_id = :userId";
        Map<String, Object> params = new HashMap<>();
        params.put("id", addressId);
        params.put("userId", userId);
        namedParameterJdbcTemplate.update(setSql, params);
    }
    
    // 查询用户的地址列表
    public List<UserAddress> findByUserId(Long userId) {
        String sql = "SELECT * FROM user_address WHERE user_id = :userId ORDER BY is_default DESC, id DESC";
        return namedParameterJdbcTemplate.query(
            sql,
            Collections.singletonMap("userId", userId),
            (rs, rowNum) -> {
                UserAddress address = new UserAddress();
                address.setId(rs.getLong("id"));
                address.setUserId(rs.getLong("user_id"));
                address.setReceiverName(rs.getString("receiver_name"));
                address.setReceiverPhone(rs.getString("receiver_phone"));
                address.setProvince(rs.getString("province"));
                address.setCity(rs.getString("city"));
                address.setDistrict(rs.getString("district"));
                address.setDetailAddress(rs.getString("detail_address"));
                address.setIsDefault(rs.getInt("is_default"));
                address.setCreatedAt(rs.getTimestamp("created_at"));
                address.setUpdatedAt(rs.getTimestamp("updated_at"));
                return address;
            });
    }
}

5.4 服务层实现

UserService:

@Service
public class UserService {
    
    private final UserRepository userRepository;
    private final UserAddressRepository addressRepository;
    private final PasswordEncoder passwordEncoder;
    
    public UserService(UserRepository userRepository, 
                      UserAddressRepository addressRepository,
                      PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.addressRepository = addressRepository;
        this.passwordEncoder = passwordEncoder;
    }
    
    // 注册新用户
    @Transactional
    public Long register(User user) {
        // 检查用户名是否已存在
        if (userRepository.findByUsername(user.getUsername()) != null) {
            throw new BusinessException("用户名已存在");
        }
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setStatus(1); // 默认启用状态
        
        // 保存用户
        return userRepository.insert(user);
    }
    
    // 用户登录
    public User login(String username, String password) {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new BusinessException("用户名或密码错误");
        }
        
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }
        
        if (user.getStatus() == 0) {
            throw new BusinessException("用户已被禁用");
        }
        
        return user;
    }
    
    // 添加用户地址
    @Transactional
    public Long addAddress(UserAddress address) {
        // 如果是默认地址,需要先清除其他默认地址
        if (address.getIsDefault() == 1) {
            addressRepository.setDefaultAddress(address.getUserId(), null);
        }
        
        return addressRepository.insert(address);
    }
    
    // 设置默认地址
    @Transactional
    public void setDefaultAddress(Long userId, Long addressId) {
        addressRepository.setDefaultAddress(userId, addressId);
    }
    
    // 获取用户地址列表
    public List<UserAddress> getUserAddresses(Long userId) {
        return addressRepository.findByUserId(userId);
    }
    
    // 分页查询用户
    public Page<User> listUsers(int page, int size) {
        return userRepository.findAll(page, size);
    }
}

5.5 控制器层实现

UserController:

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    private final UserService userService;
    
    public UserController(UserService userService) {
        this.userService = userService;
    }
    
    @PostMapping("/register")
    public ResponseEntity<Long> register(@RequestBody @Valid User user) {
        Long userId = userService.register(user);
        return ResponseEntity.ok(userId);
    }
    
    @PostMapping("/login")
    public ResponseEntity<User> login(@RequestParam String username, 
                                    @RequestParam String password) {
        User user = userService.login(username, password);
        return ResponseEntity.ok(user);
    }
    
    @GetMapping("/{userId}/addresses")
    public ResponseEntity<List<UserAddress>> getAddresses(@PathVariable Long userId) {
        List<UserAddress> addresses = userService.getUserAddresses(userId);
        return ResponseEntity.ok(addresses);
    }
    
    @PostMapping("/{userId}/addresses")
    public ResponseEntity<Long> addAddress(@PathVariable Long userId,
                                          @RequestBody @Valid UserAddress address) {
        address.setUserId(userId);
        Long addressId = userService.addAddress(address);
        return ResponseEntity.ok(addressId);
    }
    
    @PutMapping("/{userId}/addresses/{addressId}/default")
    public ResponseEntity<Void> setDefaultAddress(@PathVariable Long userId,
                                                @PathVariable Long addressId) {
        userService.setDefaultAddress(userId, addressId);
        return ResponseEntity.ok().build();
    }
    
    @GetMapping
    public ResponseEntity<Page<User>> listUsers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Page<User> users = userService.listUsers(page, size);
        return ResponseEntity.ok(users);
    }
}

六、常见问题与解决方案

6.1 性能问题排查

1. SQL 执行缓慢:

  • 使用 EXPLAIN 分析 SQL 执行计划
  • 检查是否使用了合适的索引
  • 避免全表扫描

2. 连接池耗尽:

  • 检查是否有连接泄漏 (未关闭的连接)
  • 增加连接池大小
  • 优化事务范围,减少事务持有时间

3. 批处理性能不佳:

  • 调整批处理大小
  • 考虑使用 rewriteBatchedStatements=true (MySQL)
  • 关闭自动提交

6.2 事务问题排查

1. 事务不生效:

  • 确保方法被 Spring 代理 (在同一个类中调用事务方法不会生效)
  • 检查异常是否被捕获未抛出
  • 确认方法访问修饰符不是 private/final

2. 死锁问题:

  • 按照固定顺序访问资源
  • 减少事务持有时间
  • 使用适当的隔离级别

6.3 异常处理

Spring JDBC 会将 SQLException 转换为 DataAccessException 层次结构中的异常:

异常类型

说明

BadSqlGrammarException

SQL 语法错误

InvalidResultSetAccessException

结果集访问错误

DuplicateKeyException

违反主键或唯一约束

DataIntegrityViolationException

数据完整性违反 (如非空约束)

CannotAcquireLockException

无法获取数据库锁

DeadlockLoserDataAccessException

死锁受害者

UncategorizedSQLException

未分类的 SQL 异常

最佳实践:

  1. 捕获具体的 DataAccessException 子类
  2. 提供有意义的错误信息
  3. 考虑添加重试逻辑 (对于乐观锁异常等)
@Service
public class OrderService {
    
    private final JdbcTemplate jdbcTemplate;
    
    public OrderService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    @Transactional
    public void placeOrder(Order order) {
        try {
            // 扣减库存
            String updateSql = "UPDATE products SET stock = stock - ? WHERE id = ? AND stock >= ?";
            int updated = jdbcTemplate.update(updateSql, order.getQuantity(), order.getProductId(), order.getQuantity());
            if (updated == 0) {
                throw new OutOfStockException("Product out of stock");
            }
            
            // 创建订单
            String insertSql = "INSERT INTO orders (user_id, product_id, quantity, status) VALUES (?, ?, ?, ?)";
            jdbcTemplate.update(insertSql, order.getUserId(), order.getProductId(), order.getQuantity(), "CREATED");
            
        } catch (DuplicateKeyException e) {
            throw new BusinessException("Order already exists", e);
        } catch (DataIntegrityViolationException e) {
            throw new BusinessException("Invalid order data", e);
        }
    }
}

七、扩展与进阶

7.1 多数据源配置

在实际应用中,有时需要连接多个数据库:

@Configuration
public class MultipleDataSourceConfig {
    
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    
    @Bean
    @Primary
    public JdbcTemplate primaryJdbcTemplate(DataSource primaryDataSource) {
        return new JdbcTemplate(primaryDataSource);
    }
    
    @Bean
    public JdbcTemplate secondaryJdbcTemplate(
            @Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
        return new JdbcTemplate(secondaryDataSource);
    }
    
    @Bean
    @Primary
    public PlatformTransactionManager primaryTransactionManager(
            @Qualifier("primaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    
    @Bean
    public PlatformTransactionManager secondaryTransactionManager(
            @Qualifier("secondaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

application.yml 配置:

spring:
  datasource:
    primary:
      url: jdbc:mysql://localhost:3306/primary_db
      username: root
      password: password
      driver-class-name: com.mysql.cj.jdbc.Driver
      hikari:
        maximum-pool-size: 10
    secondary:
      url: jdbc:mysql://localhost:3306/secondary_db
      username: root
      password: password
      driver-class-name: com.mysql.cj.jdbc.Driver
      hikari:
        maximum-pool-size: 5

7.2 动态数据源与路由

对于需要根据条件动态切换数据源的场景:

public class DynamicDataSource extends AbstractRoutingDataSource {
    
    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getDataSourceType();
    }
}

public class DataSourceContextHolder {
    
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
    
    public static void setDataSourceType(String dataSourceType) {
        contextHolder.set(dataSourceType);
    }
    
    public static String getDataSourceType() {
        return contextHolder.get();
    }
    
    public static void clearDataSourceType() {
        contextHolder.remove();
    }
}

@Aspect
@Component
public class DataSourceAspect {
    
    @Before("@annotation(dataSource)")
    public void beforeSwitchDataSource(JoinPoint point, DataSource dataSource) {
        DataSourceContextHolder.setDataSourceType(dataSource.value());
    }
    
    @After("@annotation(dataSource)")
    public void afterSwitchDataSource(JoinPoint point, DataSource dataSource) {
        DataSourceContextHolder.clearDataSourceType();
    }
}

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
    String value() default "primary";
}

7.3 与 MyBatis/JPA 的对比

特性

JdbcTemplate

MyBatis

JPA/Hibernate

学习曲线

灵活性

高 (直接SQL)

高 (XML/注解SQL)

中 (JPQL)

开发效率

性能

缓存支持

需手动实现

一级/二级缓存

一级/二级缓存

适合场景

简单CRUD, 需要直接控制SQL

复杂SQL, 需要SQL与对象映射

快速开发, 对象关系复杂

事务管理

支持

支持

支持

批处理

支持

支持

支持

7.4 响应式数据库访问

Spring 还提供了响应式的数据库访问方式 (R2DBC):

@Repository
public class ReactiveUserRepository {
    
    private final R2dbcEntityTemplate template;
    
    public ReactiveUserRepository(R2dbcEntityTemplate template) {
        this.template = template;
    }
    
    public Mono<User> findById(Long id) {
        return template.selectOne(
            Query.query(Criteria.where("id").is(id)), 
            User.class);
    }
    
    public Flux<User> findAll() {
        return template.select(User.class).all();
    }
    
    public Mono<Long> save(User user) {
        return template.insert(User.class)
            .using(user)
            .map(User::getId);
    }
}

八、总结与最佳实践

8.1 技术选型建议

  1. 选择 JdbcTemplate 当
  2. 需要直接控制 SQL
  3. 项目简单,不需要复杂的 ORM 功能
  4. 对性能有极高要求
  5. 已有大量 JDBC 代码需要迁移
  6. 考虑其他技术当
  7. 需要复杂对象关系映射 → JPA/Hibernate
  8. 需要灵活 SQL 但不想处理 JDBC 样板 → MyBatis
  9. 需要响应式编程 → R2DBC

8.2 性能最佳实践

  1. 连接池配置
  2. 根据系统负载调整连接池大小
  3. 设置合理的连接超时和空闲超时
  4. 监控连接池使用情况
  5. SQL 优化
  6. 使用批处理操作
  7. 合理使用索引
  8. 避免 N+1 查询问题
  9. 事务管理
  10. 尽量缩短事务范围
  11. 只读操作标记为 read-only
  12. 选择合适的事务隔离级别

8.3 代码组织建议

  1. 分层清晰
  2. Controller: 处理 HTTP 请求/响应
  3. Service: 业务逻辑,事务边界
  4. Repository: 数据访问,使用 JdbcTemplate
  5. 异常处理
  6. 在 Repository 层捕获 DataAccessException
  7. 转换为业务异常在 Service 层抛出
  8. 在 Controller 层处理异常并返回适当响应
  9. 测试策略
  10. 单元测试: 测试 Service 层 (Mock Repository)
  11. 集成测试: 测试 Repository 层 (真实数据库)
  12. 使用 @SpringBootTest 进行端到端测试
@SpringBootTest
public class UserRepositoryIntegrationTest {
    
    @Autowired
    private UserRepository userRepository;
    
    @Test
    @Transactional
    public void testFindByUsername() {
        User user = new User();
        user.setUsername("testuser");
        user.setPassword("password");
        user.setEmail("test@example.com");
        userRepository.insert(user);
        
        User found = userRepository.findByUsername("testuser");
        assertNotNull(found);
        assertEquals("test@example.com", found.getEmail());
    }
    
    @Test
    public void testFindByUsernameNotFound() {
        User found = userRepository.findByUsername("nonexistent");
        assertNull(found);
    }
}

8.4 未来演进方向

  1. 云原生适配
  2. 使用服务网格管理数据库连接
  3. 适配 Kubernetes 环境
  4. 混合持久化
  5. JdbcTemplate 与 JPA/MyBatis 混合使用
  6. 不同模块使用不同数据访问技术
  7. 数据分片
  8. 实现基于分片键的数据路由
  9. 支持水平扩展
  10. 多模数据库
  11. 同一应用中使用关系型和 NoSQL 数据库
  12. 根据数据特性选择合适存储

通过本指南,您应该已经全面掌握了 Spring Boot JDBC 和 JdbcTemplate 的核心概念、使用方法和最佳实践。无论是简单的 CRUD 操作还是复杂的事务管理,JdbcTemplate 都提供了强大而灵活的支持。根据项目需求合理运用这些技术,可以构建出高效、可靠的数据访问层。

关注我?别别别,我怕你笑出腹肌找我赔钱。


头条对markdown的文章显示不太友好,想了解更多的可以关注微信公众号:“Eric的技术杂货库”,后期会有更多的干货以及资料下载。

相关推荐

Spring IoC Container 原理解析

IoC、DI基础概念关于IoC和DI大家都不陌生,我们直接上martinfowler的原文,里面已经有DI的例子和spring的使用示例...

SQL注入:程序员亲手打开的潘多拉魔盒,如何彻底封印它?

一、现象:当你的数据库开始"说话",灾难就来了场景还原:...

Java核心知识3:异常机制详解

1什么是异常异常是指程序在运行过程中发生的,由于外部问题导致的运行异常事件,如:文件找不到、网络连接失败、空指针、非法参数等。异常是一个事件,它发生在程序运行期间,且中断程序的运行。...

MyBatis常用工具类三-使用SqlRunner操作数据库

MyBatis中提供了一个非常实用的、用于操作数据库的SqlRunner工具类,该类对JDBC做了很好的封装,结合SQL工具类,能够很方便地通过Java代码执行SQL语句并检索SQL执行结果。SqlR...

爆肝2W字梳理50道计算机网络必问面试题

1.说说HTTP常用的状态码及其含义?思路:这道面试题主要考察候选人,是否掌握HTTP状态码这个基础知识点。...

SpringBoot整合Vue3实现发送邮箱验证码功能

1.效果演示2.思维导图...

最全JAVA面试题及答案(200+)

Java基础1.JDK和JRE有什么区别?JDK:JavaDevelopmentKit的简称,Java开发工具包,提供了Java的开发环境和运行环境。JRE:JavaRunti...

Java程序员找工作翻车现场!你的项目描述踩了这几个坑?

Java程序员找工作翻车现场!你的项目描述踩了这几个坑?噼里啪啦敲了三年代码,简历一投石沉大海?兄弟,问题可能出在项目描述上!知道为什么面试官看你的项目像看天书吗?因为你写了三个致命雷区:第一,把项目...

2020最新整理JAVA面试题附答案,包含19个模块共208道面试题

包含的模块:本文分为十九个模块,分别是:Java基础、容器、多线程、反射、对象拷贝、JavaWeb、异常、网络、设计模式、Spring/SpringMVC、SpringBoot/Spring...

底层原理深度解析:equals() 与 == 的 JVM 级运作机制

作为Java开发者,你是否曾在集合操作时遇到过对象比较的诡异问题?是否在使用HashMap时发现对象丢失?这些问题往往源于对equals()和==的误解,以及实体类中这两个方法的不当实...

雪花算法,什么情况下发生 ID 冲突?

分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的...

50个Java编程技巧,免费送给大家

一、语法类技巧1.1.使用三元表达式普通:...

如何规划一个合理的JAVA项目工程结构

由于阿里Java开发手册对于工程结构的描述仅限于1、2节简单的概述,不能满足多样的实际需求,本文根据多个项目中工程的实践,分享一种较为合理实用的工程结构。工程结构的原则有依据、实用。有依据的含义是指做...

Java 编程技巧之单元测试用例编写流程

温馨提示:本文较长,同学们可收藏后再看:)前言...

MyBatis核心源码解读:SQL执行流程的奇妙之旅

MyBatis核心源码解读:SQL执行流程的奇妙之旅大家好呀!今天咱们要来一场既烧脑又有趣的旅程——探索MyBatis这个强大框架的核心秘密。你知道吗?当你在项目里轻轻松松写一句“select*f...

取消回复欢迎 发表评论: