SpringBoot---数据源和SessionFactory配置

本文主要介绍了如何在SpringBoot项目中配置Mybatis,包括数据源设置和SessionFactory的创建步骤,帮助读者理解如何在SpringBoot环境下实现数据库操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


DataSourceConfiguration.java


@Configuration
// 配置mybatis mapper的扫描路径
@MapperScan("ink.xlr.demo.dao")
public class DataSourceConfiguration {
    @Value("${jdbc.driver}")
    private String jdbcDriver;
    @Value("${jdbc.url}")
    private String jdbcUrl;
    @Value("${jdbc.user}")
    private String jdbcUsername;
    @Value("${jdbc.password}")
    private String jdbcPassword;

    @Bean(name = "dataSource")
    public ComboPooledDataSource createDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(jdbcDriver);
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUser(jdbcUsername);
        dataSource.setPassword(jdbcPassword);
        // 关闭连接后 不自动commit
        dataSource.setAutoCommitOnClose(false);
        return dataSource;
    }
}

application.properties

# tomcat运行端口
server.port=8082
# 项目根路径
server.servlet.context-path=/demo

# c3p0数据源配置
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springboot_test?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
jdbc.user=root
jdbc.password=123456789

# Mybatis配置文件
mybatis_config_file=mybatis-config.xml
# mapper文件路径
mapper_path=/mapper/**.xml
# 实体类路径
entity_package=ink.xlr.demo.entity

SessionFactoryConfiguration.java



@Configuration
public class SessionFactoryConfiguration {

    // mybatis-config.xml配置文件的路径
    @Value("${mybatis_config_file}")
    private String mybatisConfigFilePath;

    // mybatis mapper文件所在路径
    @Value("${mapper_path}")
    private String mapperPath;

    // 实体类所在的package
    @Value("${entity_package}")
    private String entityPackage;

    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;

    @Bean(name="sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 扫描mybatis配置文件
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
        // 扫描相关mapper文件
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
        // 调用dataSource
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 映射实体类
        sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
        return sqlSessionFactoryBean;
    }
}

pom.xml

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        
### 实现Spring Boot与MyBatis-Plus多数据源插入操作 #### 配置依赖项 为了使项目能够顺利运行并支持多数据源功能,在`pom.xml`文件中需引入必要的依赖包。这包括但不限于Spring Boot Starter、MyBatis-Plus及其对应的数据库驱动程序。 ```xml <dependencies> <!-- Spring Boot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <!-- MySQL Driver (或其他适用的数据库驱动) --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- 其他可能需要的依赖... --> </dependencies> ``` #### 数据源配置 在项目的`application.yml`或`application.properties`文件内定义至少两个不同的数据源连接信息,分别为主库(`primary`)副本库(`replica`)设置URL、用户名、密码及JDBC驱动类名等参数[^4]。 ```yaml spring: datasource: primary: url: jdbc:mysql://localhost:3306/primary_db?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver replica: url: jdbc:mysql://localhost:3306/replica_db?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver ``` #### 创建自定义DataSourceConfig类 编写一个名为`DynamicDataSourceConfig.java`的新Java类用于管理动态切换的数据源逻辑,并注册到Spring容器中作为Bean实例。此方法允许应用程序根据业务需求灵活选择目标数据库执行SQL语句。 ```java import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @MapperScan(basePackages = "com.example.mapper", sqlSessionFactoryRef="sqlSessionFactory") public class DynamicDataSourceConfig { @Autowired private DataSourceProperties dataSourceProperties; // 假设已创建此类获取YAML配置 /** * 构建SqlSessionFactory Bean对象 */ @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource) throws Exception { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dynamicDataSource); // 可选:添加其他配置... return sessionFactory.getObject(); } } ``` 请注意上述代码片段仅展示了部分核心组件;实际应用时还需考虑更多细节如异常处理机制、事务传播行为等。 #### 编写Service层接口服务实现类 针对每一个实体表设计相应的DAO接口继承BaseMapper<T>, T代表具体模型类。接着为每个模块建立各自的service接口与其impl实现类完成CRUD基本操作封装。 ```java // UserMapper.java package com.example.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.entity.UserEntity; import org.apache.ibatis.annotations.Mapper; @Mapper public interface UserMapper extends BaseMapper<UserEntity> {} // UserServiceImpl.java @Service @Slf4j public class UserServiceImpl implements IUserService { @Resource private UserMapper userMapper; @Override public boolean saveUser(UserEntity entity){ int result = this.userMapper.insert(entity); log.info("Insert operation affected {} rows.",result); return result > 0 ; } // 更多功能待补充... } ``` 以上即是在Spring Boot环境下利用MyBatis-Plus框架搭建起一套完整的多数据源架构体系的过程概述。通过这种方式可以有效提升系统的灵活性与扩展能力,满足复杂应用场景下的多样化需求[^1][^2].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值