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

相关推荐
羱滒3 分钟前
sql调优之数据库开发规范
java·数据库·数据库开发
程序员Android5 分钟前
MTK多帧拍照流程分析
数据库
不剪发的Tony老师7 分钟前
Apache Doris:一款高性能的实时数据仓库
数据库·数据仓库
甜可儿18 分钟前
redis序列化设置
数据库·redis
GGBondlctrl23 分钟前
【SpringBoot】论坛项目中如何进行实现发布文章,以及更新对应数据库的数据更新
数据库·springboot项目·三层设计思想·文章发布项目
若云止水36 分钟前
Ubuntu 下 nginx-1.24.0 源码分析 - ngx_init_cycle 函数 - 详解(4)
数据库·nginx·ubuntu
jay丿1 小时前
Django模板系统深入
数据库·django·sqlite
帅的飞起来1 小时前
设计模式--spring中用到的设计模式
java·spring·设计模式
千层冷面1 小时前
Redis除了做缓存还能做什么?
数据库·redis·缓存
码有余悸3 小时前
Redis:高性能的键值存储系统
数据库·redis·缓存