简介
我们这里集成一下Mybatis的多数据源情况。
什么是多数据源:多数据源指的是如果一个web项目用到了多个数据库,那么就需要连接多个数据库操作,这就是多数据源。
多数据源的好处:减轻服务器和数据库的压力。
配置数据库连接池
连接池HikariDataSource,连接字符串属性名是jdbcUrl。
#数据源1
spring.datasource.test1.driverClassName=com.mysql.jdbc.Driver
spring.datasource.test1.jdbcUrl=jdbc:mysql://localhost:3306/test1?useUnicode=true&useSSL=false&characterEncoding=utf8
spring.datasource.test1.username=root
spring.datasource.test1.password=123456
#数据源2
spring.datasource.test2.driverClassName=com.mysql.jdbc.Driver
spring.datasource.test2.jdbcUrl=jdbc:mysql://localhost:3306/test2?useUnicode=true&useSSL=false&characterEncoding=utf8
spring.datasource.test2.username=root
spring.datasource.test2.password=123456
每个配置源配置一个加载类
我们只需在配置文件中配置一下我们的两个数据源,然后分别写一个配置类加载进去就可以了。
数据源1:DataSource1Config
import org.apache.ibatis.logging.stdout.StdOutImpl;
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.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import javax.sql.DataSource;
@Configuration
//扫描指定的mapper接口包,和会话工厂类
@MapperScan(basePackages = "com.entor.mapper.test1",sqlSessionFactoryRef = "sqlSessionFactory1")
public class DataSource1Config {
@Bean(value = "dataSource1")
//加载application.properties文件中前缀为spring.datasource.test1的配置项,根据属性名称(去掉前缀)自动赋值给数据源的对象
@ConfigurationProperties(prefix = "spring.datasource.test1")
@Primary//当装配有多个时,默认使用这个
public DataSource dataSource1() {
return DataSourceBuilder.create().build();//springboot提供的方法
}
@Bean(value = "sqlSessionFactory1")
@Primary//当装配有多个时,默认使用这个
public SqlSessionFactory sqlSessionFactory1(@Qualifier("dataSource1") DataSource dataSource1) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource1);
bean.setTypeAliasesPackage("com.entor.entity");
// PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// bean.setMapperLocations(resolver.getResources("mapper/*.xml"));
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setLogImpl(StdOutImpl.class);
configuration.setMapUnderscoreToCamelCase(true);
configuration.setCacheEnabled(true);
bean.setConfiguration(configuration);
return bean.getObject();
}
@Bean(value = "transactionManager1")
@Primary//当装配有多个时,默认使用这个
public TransactionManager transactionManager(@Qualifier("dataSource1") DataSource dataSource1) {
return new DataSourceTransactionManager(dataSource1);
}
}
**数据源2:DataSource2Config **
import org.apache.ibatis.logging.stdout.StdOutImpl;
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.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import javax.sql.DataSource;
@Configuration
//扫描指定的mapper接口包,和会话工厂类
@MapperScan(basePackages = "com.entor.mapper.test2",sqlSessionFactoryRef = "sqlSessionFactory2")
public class DataSource2Config {
@Bean(value = "dataSource2")
//加载application.properties文件中前缀为spring.datasource.test2的配置项,根据属性名称(去掉前缀)自动赋值给数据源的对象
@ConfigurationProperties(prefix = "spring.datasource.test2")
public DataSource dataSource2() {
return DataSourceBuilder.create().build();//springboot提供的方法
}
@Bean(value = "sqlSessionFactory2")
public SqlSessionFactory sqlSessionFactory2(@Qualifier("dataSource2") DataSource dataSource2) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource2);
bean.setTypeAliasesPackage("com.entor.entity");
// PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// bean.setMapperLocations(resolver.getResources("mapper/*.xml"));
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setLogImpl(StdOutImpl.class);
configuration.setMapUnderscoreToCamelCase(true);
configuration.setCacheEnabled(true);
bean.setConfiguration(configuration);
return bean.getObject();
}
@Bean(value = "transactionManager2")
public TransactionManager transactionManager(@Qualifier("dataSource2") DataSource dataSource2) {
return new DataSourceTransactionManager(dataSource2);
}
}
mapper层
test1.UserMapper
public interface UserMapper {
@Insert("insert into user(name)values(#{name})")
public void add(User user);
}
test2.RoleMapper
public interface RoleMapper {
@Insert("insert into role(name)values(#{name})")
void add(Role role);
}
service层
接口:MultiDataSourceService
@Transactional
public interface MultiDataSourceService {
public void add(User user, Role role);
}
Impl
@Service
@Transactional
public class MultiDataSourceServiceImpl implements MultiDataSourceService {
@Autowired(required = false)
private UserMapper userMapper;
@Autowired(required = false)
private RoleMapper roleMapper;
@Override
public void add(User user, Role role) {
userMapper.add(user);
roleMapper.add(role);
}
}
controller
@RestController
public class MultiDataSourceController {
@Autowired
private MultiDataSourceService multiDataSourceService;
@RequestMapping(value = "/multiAdd")
public String add(){
User user = new User();
user.setName("张三");
Role role = new Role();
role.setName("普通用户");
multiDataSourceService.add(user,role);
return "新增成功";
}
}
启动类
注意开启事务开启
@SpringBootApplication
@EnableTransactionManagement
public class SpringbootMybatis0420Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatis0420Application.class, args);
}
}