CREATE TABLE `user` (
`id` bigint(20) NOT NULL,
`name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
org.mybatis.spring.boot</groupId>
mybatis-spring-boot-starter</artifactId>
2.1.3</version>
</dependency>
mysql</groupId>
mysql-connector-java</artifactId>
runtime</scope>
</dependency>
org.projectlombok</groupId>
lombok</artifactId>
true</optional>
</dependency>
spring:
datasource:
# 第一个数据源
first:
# 多数据源配置中url替换成jdbc-url
jdbc-url: jdbc:mysql://localhost:3306/bg-learnsp?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
# 第二个数据源
second:
jdbc-url: jdbc:mysql://localhost:3306/bg-learnsp-second?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:/mapper/**/*.xml # mapper文件位置
logging:
level:
root: info
com.learn.mapper: debug
注意:多数据源配置中,url属性名称需要替换成jdbc-url。
@Configuration
@MapperScan(basePackages = "com.learn.mapper.first", sqlSessionFactoryRef = "firstSqlSessionFactory")
public class FirstDataSourceConfig {
@Bean(name = "firstDataSource")
// 表示这个数据源是默认数据源
@Primary
// prefix表示参数的前缀
@ConfigurationProperties(prefix = "spring.datasource.first")
public DataSource firstDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "firstSqlSessionFactory")
// 表示这个数据源是默认数据源
@Primary
// @Qualifier表示查找Spring容器中名字为test1DataSource的对象
public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
// mapper文件位置
bean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/first/**/*.xml"));
return bean.getObject();
}
@Bean("firstSqlSessionTemplate")
// 表示这个数据源是默认数据源
@Primary
public SqlSessionTemplate firstSqlSessionTemplate(
@Qualifier("firstSqlSessionFactory") SqlSessionFactory sessionFactory) {
return new SqlSessionTemplate(sessionFactory);
}
}
@Configuration
@MapperScan(basePackages = "com.learn.mapper.second", sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDataSourceConfig {
@Bean(name = "secondDataSource")
// prefix表示参数的前缀
@ConfigurationProperties(prefix = "spring.datasource.second")
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondSqlSessionFactory")
// @Qualifier表示查找Spring容器中名字为test1DataSource的对象
public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/second/**/*.xml"));
return bean.getObject();
}
@Bean("secondSqlSessionTemplate")
public SqlSessionTemplate secondSqlSessionTemplate(
@Qualifier("secondSqlSessionFactory") SqlSessionFactory sessionFactory) {
return new SqlSessionTemplate(sessionFactory);
}
}
@Data
public class FirstUser {
private Long id;
private String name;
private Integer age;
}
@Data
public class SecondUser {
private Long id;
private String name;
private Integer age;
}
public interface FirstUserMapper {
/**
* 通过id获取用户信息
*
* @param id
* @return
*/
@Select("select * from user where id = #{id}")
public FirstUser getFirstUserById(Long id);
/**
* 保存用户信息
*
* @param firstUser
* @return
*/
public int insertFirstUser(FirstUser firstUser);
}
public interface SecondUserMapper {
/**
* 通过id获取用户信息
*
* @param id
* @return
*/
@Select("select * from user where id = #{id}")
public SecondUser getSecondUserById(Long id);
/**
* 保存用户信息
*
* @param secondUser
* @return
*/
public int insertSecondUser(SecondUser secondUser);
}
这里Mapper文件使用了注解和xml文件相结合的方式。
"1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
"com.learn.mapper.first.FirstUserMapper">
"insertFirstUser">
INSERT INTO USER(ID,NAME, AGE) VALUES(#{id},#{name}, #{age})
</insert>
</mapper>
"1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
"com.learn.mapper.second.SecondUserMapper">
"insertSecondUser">
INSERT INTO USER(ID,NAME, AGE) VALUES(#{id},#{name}, #{age})
</insert>
</mapper>
@SpringBootTest
class SpLearnMybatisMultiDataSourceApplicationTests {
@Autowired
private FirstUserMapper firstUserMapper;
@Autowired
private SecondUserMapper secondUserMapper;
@Test
void testUserMapper() {
FirstUser firstUser = new FirstUser();
firstUser.setId(7777L);
firstUser.setName("我是First数据源保存的");
firstUser.setAge(100);
//保存
firstUserMapper.insertFirstUser(firstUser);
//查询
System.out.println(firstUserMapper.getFirstUserById(7777L));
SecondUser secondUser = new SecondUser();
secondUser.setId(8888L);
secondUser.setName("我是Second数据源保存的");
secondUser.setAge(0);
//保存
secondUserMapper.insertSecondUser(secondUser);
//查询
System.out.println(secondUserMapper.getSecondUserById(8888L));
}
}