SpringBoot 整合 Druid 数据源教程 - 详细步骤及代码示例

本文将详细介绍如何在 SpringBoot 项目中整合 Druid 数据源,并提供完整的代码示例,帮助你快速上手。

1. 添加 Maven 依赖

首先,在你的 pom.xml 文件中添加 Druid 和 Spring JDBC 的依赖:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.21</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

2. 配置 Druid 数据源

在 application.properties 或 application.yml 文件中配置 Druid 数据源,例如:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

# Druid 配置
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.validation-query=SELECT 1

3. 开启事务管理和扫描 Mapper 接口

在 SpringBoot 启动类中添加 @EnableTransactionManagement 和 @MapperScan 注解,用于开启事务管理和扫描 Mapper 接口:

@SpringBootApplication
@EnableTransactionManagement
@MapperScan('com.example.mapper')
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

4. 定义 Mapper 接口

在 Mapper 接口中使用 @Mapper 注解,并继承 MyBatis 的 Mapper 接口,例如:

@Mapper
public interface UserMapper extends tk.mybatis.mapper.common.Mapper<User> {
    // 其他自定义方法
}

5. 在 Service 层开启事务

在 Service 层使用 @Transactional 注解开启事务:

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Transactional
    public void addUser(User user) {
        userMapper.insert(user);
    }

    // 其他自定义方法
}

总结

以上步骤详细介绍了如何在 SpringBoot 项目中整合 Druid 数据源。你可以根据自己的业务需求进行调整和扩展。

SpringBoot 整合 Druid 数据源教程 - 详细步骤及代码示例

原文地址: https://www.cveoy.top/t/topic/lNBD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录