String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
@Mapper
public interface MyMapper {
// 方法定义
}
@Configuration
@MapperScan("com.example.mapper")
public class MyBatisConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/mydatabase");
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
return sessionFactory.getObject();
}
# application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=password
# 数据库1配置
spring.datasource.db1.url=jdbc:mysql://localhost:3306/db1
spring.datasource.db1.username=root
spring.datasource.db1.password=123456
spring.datasource.db1.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据库2配置
spring.datasource.db2.url=jdbc:oracle:thin:@localhost:1521:ORCL
spring.datasource.db2.username=user1
spring.datasource.db2.password=password1
spring.datasource.db2.driver-class-name=oracle.jdbc.driver.OracleDriver
@Configuration
public class MyBatisConfig {
@Bean(name = "dataSource1")
@ConfigurationProperties(prefix = "spring.datasource.db1")
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
@Bean(name = "sqlSessionFactory1")
public SqlSessionFactory sqlSessionFactory1(@Qualifier("dataSource1") DataSource dataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
// 其他配置(如 mybatis-config.xml 文件的路径)
return factoryBean.getObject();
}
@Bean(name = "transactionManager1")
public DataSourceTransactionManager transactionManager1(@Qualifier("dataSource1") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
// 为数据库2配置类似的数据源、SqlSessionFactory 和事务管理器
// ...
}
public interface UserMapper {
User selectUserById(int id);
}
public interface UserMapper {
@Select("SELECT id, name FROM user WHERE age > 18 " +
"UNION ALL " +
"SELECT id, name FROM user WHERE name LIKE '%John%'")
List selectUsersByUnion();
}
参与评论
手机查看
返回顶部