【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-jdbcmysql-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 的自动配置以简化开发流程。

相关推荐
AI-好学者几秒前
阶段一-图数据库基础与PropertyGraph模型
数据库·rag·knowledge graph·graphrag
其实防守也摸鱼1 小时前
运维--学习阶段问题解答(1)(自测)
linux·运维·服务器·数据库·学习·自动化·命令模式
懒鸟一枚2 小时前
深入理解 Linux 内存、Swap 交换分区与分页机制的关系
java·linux·数据库
龙仔7252 小时前
SQL Server 创建只读账号完整操作(分两种场景:SSMS图形界面 + T-SQL脚本)
数据库·sql·oracle
霁月的小屋2 小时前
生产环境中的事务实践——银行系统上线记(四)
数据库
Database_Cool_2 小时前
AI 应用数据底座首选:阿里云 PolarDB 为大模型 RAG 提供一体化支撑
数据库·阿里云
玖玥拾2 小时前
C# 语言进阶(十五)C# 游戏服务端 MySQL 数据库
服务器·开发语言·网络·数据库·mysql·c#
IvorySQL4 小时前
PG 日报|社区讨论重构 pg_hba 配置文件格式
数据库·人工智能·postgresql·重构·ivorysql
逝水无殇4 小时前
C# 文件的输入与输出详解
开发语言·数据库·后端·c#