【Spring Framework】MySQL 数据库连接配置

Spring Framework 是一个非常流行的 Java 企业级应用程序开发框架,其中连接 MySQL 数据库是常见的需求之一。在 Spring 中,可以使用 XML 配置、Java 配置(基于注解),以及 Spring Boot 中的自动配置来连接 MySQL 数据库。

下面我将详细介绍如何使用这些不同的方式来配置 MySQL 数据库连接。

1. 使用 XML 配置 MySQL 数据库连接

1.1 添加 MySQL JDBC 驱动依赖

首先,确保你的项目中包含 MySQL JDBC 驱动。对于 Maven 项目,在 pom.xml 中添加以下依赖:

xml 复制代码
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.32</version> <!-- 请根据需要选择合适的版本 -->
</dependency>

如果使用 Gradle,你可以在 build.gradle 中添加以下内容:

groovy 复制代码
dependencies {
    implementation 'mysql:mysql-connector-java:8.0.32'
}

1.2 XML 配置文件

使用 Spring 的 XML 配置文件来配置 MySQL 数据源和 JdbcTemplate。这里使用 Apache Commons DBCP 作为数据源的实现。

xml 复制代码
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mydatabase?useSSL=false&amp;serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="password"/>
        <!-- 可选属性 -->
        <property name="initialSize" value="5"/>
        <property name="maxTotal" value="10"/>
        <property name="maxIdle" value="5"/>
        <property name="minIdle" value="2"/>
    </bean>

    <!-- 配置 JdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 启用注解驱动的事务管理 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

1.3 使用 JdbcTemplate

现在,可以在你的服务类中注入 JdbcTemplate 以执行数据库操作:

java 复制代码
package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional
    public void insertUser(String name, String email) {
        String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
        jdbcTemplate.update(sql, name, email);
    }
    
    public void deleteUser(int userId) {
        String sql = "DELETE FROM users WHERE id = ?";
        jdbcTemplate.update(sql, userId);
    }
    
    public void updateUser(int userId, String newName) {
        String sql = "UPDATE users SET name = ? WHERE id = ?";
        jdbcTemplate.update(sql, newName, userId);
    }

    public List<User> getAllUsers() {
        String sql = "SELECT * FROM users";
        return jdbcTemplate.query(sql, (rs, rowNum) ->
                new User(rs.getInt("id"), rs.getString("name"), rs.getString("email")));
    }
}

1.4 测试类

编写一个简单的测试类来验证连接和 CRUD 操作:

java 复制代码
package com.example;

import com.example.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserService userService = context.getBean(UserService.class);

        // 插入用户
        userService.insertUser("Alice", "alice@example.com");
        
        // 获取所有用户
        List<User> users = userService.getAllUsers();
        users.forEach(System.out::println);
        
        // 更新用户
        userService.updateUser(1, "Alice Updated");

        // 删除用户
        userService.deleteUser(1);
    }
}

2. 使用 Java 注解配置 MySQL 数据库连接

除了使用 XML 文件配置外,Spring 还支持使用 Java 注解来配置应用程序。

2.1 Java 配置类

首先创建一个 Java 配置类,用于设置数据源和 JdbcTemplate:

java 复制代码
package com.example.config;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@ComponentScan(basePackages = "com.example")
@EnableTransactionManagement
public class AppConfig {

    @Bean
    public BasicDataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/mydatabase?useSSL=false&serverTimezone=UTC");
        dataSource.setUsername("root");
        dataSource.setPassword("password");

        // 可选配置
        dataSource.setInitialSize(5);
        dataSource.setMaxTotal(10);
        dataSource.setMaxIdle(5);
        dataSource.setMinIdle(2);

        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource());
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
}

2.2 使用 JdbcTemplate

与 XML 配置中的示例一样,我们在服务类中注入 JdbcTemplate 来执行数据库操作:

java 复制代码
package com.example.service;

import com.example.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional
    public void insertUser(String name, String email) {
        String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
        jdbcTemplate.update(sql, name, email);
    }
    
    public void deleteUser(int userId) {
        String sql = "DELETE FROM users WHERE id = ?";
        jdbcTemplate.update(sql, userId);
    }
    
    public void updateUser(int userId, String newName) {
        String sql = "UPDATE users SET name = ? WHERE id = ?";
        jdbcTemplate.update(sql, newName, userId);
    }

    public List<User> getAllUsers() {
        String sql = "SELECT * FROM users";
        return jdbcTemplate.query(sql, (rs, rowNum) ->
                new User(rs.getInt("id"), rs.getString("name"), rs.getString("email")));
    }
}

2.3 测试类

编写一个简单的测试类来验证连接和 CRUD 操作:

java 复制代码
package com.example;

import com.example.config.AppConfig;
import com.example.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.List;

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        UserService userService = context.getBean(UserService.class);

        // 插入用户
        userService.insertUser("Alice", "alice@example.com");
        
        // 获取所有用户
        List<User> users = userService.getAllUsers();
        users.forEach(System.out::println);
        
        // 更新用户
        userService.updateUser(1, "Alice Updated");

        // 删除用户
        userService.deleteUser(1);
    }
}

3. 使用 Spring Boot 自动配置 MySQL 数据库连接

Spring Boot 提供了自动配置的能力,使得我们可以通过简单的配置文件来实现数据库连接。

3.1 创建 Spring Boot 项目

首先,创建一个新的 Spring Boot 项目,并添加 spring-boot-starter-jdbc 和 mysql-connector-java 依赖。

在 pom.xml 中添加以下依赖:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.32</version>
</dependency>

3.2 配置 application.properties

在 src/main/resources 目录下的 application.properties 文件中配置数据库连接信息:

properties 复制代码
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# 可选配置
spring.datasource.initial-size=5
spring.datasource.max-active=10
spring.datasource.max-idle=5
spring.datasource.min-idle=2

3.3 使用 JdbcTemplate

Spring Boot 自动配置了 JdbcTemplate,我们只需在服务类中注入它即可:

java 复制代码
package com.example.service;

import com.example.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional
    public void insertUser(String name, String email) {
        String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
        jdbcTemplate.update(sql, name, email);
    }
    
    public void deleteUser(int userId) {
        String sql = "DELETE FROM users WHERE id = ?";
        jdbcTemplate.update(sql, userId);
    }
    
    public void updateUser(int userId, String newName) {
        String sql = "UPDATE users SET name = ? WHERE id = ?";
        jdbcTemplate.update(sql, newName, userId);
    }

    public List<User> getAllUsers() {
        String sql = "SELECT * FROM users";
        return jdbcTemplate.query(sql, (rs, rowNum) ->
                new User(rs.getInt("id"), rs.getString("name"), rs.getString("email")));
    }
}

3.4 启动类

创建一个 Spring Boot 启动类:

java 复制代码
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

3.5 使用 CommandLineRunner 进行测试

使用 Spring Boot 提供的 CommandLineRunner 接口进行简单测试:

java 复制代码
package com.example;

import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DatabaseTestRunner implements CommandLineRunner {

    @Autowired
    private UserService userService;

    @Override
    public void run(String... args) throws Exception {
        // 插入用户
        userService.insertUser("Alice", "alice@example.com");

        // 获取所有用户
        List<User> users = userService.getAllUsers();
        users.forEach(System.out::println);

        // 更新用户
        userService.updateUser(1, "Alice Updated");

        // 删除用户
        userService.deleteUser(1);
    }
}

运行 Spring Boot 应用程序后,程序将执行 CommandLineRunner 中的代码,进行数据库的 CRUD 操作。

4. 总结

Spring Framework 提供了多种方式来配置和连接 MySQL 数据库:

  1. XML 配置:适用于传统项目,使用 XML 文件配置数据源和 JdbcTemplate。
  2. Java 注解配置:更现代化的方法,使用 Java 配置类来定义数据源和 JdbcTemplate。
  3. Spring Boot 自动配置:最简便的方式,利用 Spring Boot 的自动配置功能,通过配置文件定义数据库连接。

每种方式都有其适用的场景,选择合适的配置方式可以提高开发效率和代码可维护性。通常,现代应用程序会倾向于使用 Spring Boot 的自动配置以简化开发流程。

相关推荐
小白男神4 天前
MySQL进阶学习四(存储过程、游标、触发器)
mysql
这个DBA有点耶4 天前
MVCC深入:Read View、版本链与快照读——InnoDB并发控制的内核
数据库·mysql·架构
DBA_G4 天前
从地面到云霄:GBase数据库在民航三大场景的落地实践
数据库
自由能燃气设备4 天前
商用全预混低氮冷凝锅炉免费方案vs付费方案对比+选型避坑指南
大数据·数据库·人工智能
科创致远4 天前
科创致远 ESOP 系统核心效能与实战价值展示
大数据·数据库·人工智能·精益工程
kybs19914 天前
全球灾害数据分析可视化 毕业设计-附源码66794
vue.js·spring boot·mysql·安全·django·c#·asp.net
Bingo_BIG4 天前
Java Spring框架:单表的查询、新增、修改、删除、导入、导出
java·spring·前后端
2601_962218614 天前
万象生鲜系统称重自动多退少补算法解决生鲜非标品痛点
大数据·数据库·人工智能·python·算法
程序猿_极客4 天前
【免费】分享一套优质的基于SSM的校园失物招领系统的设计与实现,源码+文档+视频详解(讲解)
java·mysql·ssm·课程设计·失物招领系统
张洛闻Eren4 天前
k8s云原生【第十课】:水平 Pod 自动扩缩容
运维·数据库·云原生·kubernetes·github