自定义数据源代码 java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 import com.zaxxer.hikari.HikariDataSource; import org.apache.ibatis.logging.stdout.StdOutImpl; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.sql.DataSource; @Configuration @MapperScan(basePackages = {"cn.tofuwine.dao"}, sqlSessionTemplateRef = "customSqlSessionTemplate") // 这个注解是可选的,你可以将你的数据库配置提取到单独的文件进行存储 @PropertySource("custom_datasource.properties") public class CustomDataSourceConfiguration { @Bean("customDataSource") @ConfigurationProperties(prefix = "custom.datasource") public HikariDataSource customDataSource() { return DataSourceBuilder.create().type(HikariDataSource.class).build(); } @Bean("customSqlSessionFactory") public SqlSessionFactory customSqlSessionFactory(@Qualifier("customDataSource") DataSource dataSource) throws Exception { // 若使用 Mybatis-Plus, 此处应使用 com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/**/*.xml")); // 若使用 Mybatis-Plus, 此处应使用 com.baomidou.mybatisplus.core.MybatisConfiguration org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration(); configuration.setLogImpl(StdOutImpl.class); configuration.setMapUnderscoreToCamelCase(true); bean.setConfiguration(configuration); return bean.getObject(); } @Bean("customSqlSessionTemplate") public SqlSessionTemplate customSqlSessionTemplate(@Qualifier("customSqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } } 依赖说明 Gradle build.gradle 1 2 3 4 5 6 7 8 9 10 11 12 13 dependencies { implementation("org.springframework.boot:spring-boot-starter-data-jdbc") runtimeOnly("com.mysql:mysql-connector-j") // 以下二选一 (版本自行修改) // 1. MyBatis implementation("org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.3") testImplementation("org.mybatis.spring.boot:mybatis-spring-boot-starter-test:3.0.3") // 2. MyBatis-Plus implementation("com.baomidou:mybatis-plus-boot-starter:3.5.7") testImplementation("com.baomidou:mybatis-plus-boot-starter-test:3.5.7") }
感谢您的耐心阅读!来选个表情,或者留个评论吧!