Spring Boot最大的特点是简化开发,因此使用Java Config实现去xml配置,本文将使用这种方式完成对阿里云ADS和RDS两个产品的多数据源配置。同时,会用到阿里巴巴的开源数据源Druid。
依赖
- 因为ADS和RDS都兼容mysql的JDBC实现,因此工程只需要依赖mysql的driver。
- Spring Boot易用性的特点是通过Starter实现的,我们只需依赖mybatis的spring-boot-starter即可。
- Druid是数据源。
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<properties>
<mysql-connector-java.version>5.1.34</mysql-connector-java.version>
<druid.version>1.0.18</druid.version>
<mybatis-spring-boot-starter.version>1.1.1</mybatis-spring-boot-starter.version>
</properties>
数据源配置
多数据源配置要求必须有一个是『主』,我们将RDS设定为主,配置如下:
@Configuration
@MapperScan(basePackages = RdsDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "rdsSqlSessionFactory")
public class RdsDataSourceConfig {
static final String PACKAGE = "com.aliyun.xxx.repository.mybatis.rds";
@Value("${xxx_mysql_url}")
private String dbUrl;
@Value("${xxx_mysql_username}")
private String dbUser;
@Value("${xxx_mysql_password}")
private String dbPassword;
@Bean(name = "rdsDataSource")
@Primary
public DataSource rdsDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl(dbUrl);
dataSource.setUsername(dbUser);
dataSource.setPassword(dbPassword);
return dataSource;
}
@Bean(name = "rdsTransactionManager")
@Primary
public DataSourceTransactionManager rdsTransactionManager() {
return new DataSourceTransactionManager(rdsDataSource());
}
@Bean(name = "rdsSqlSessionFactory")
@Primary
public SqlSessionFactory rdsSqlSessionFactory(@Qualifier("rdsDataSource") DataSource rdsDataSource) throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(rdsDataSource);
return sessionFactory.getObject();
}
}
@Value
将获取Spring Boot全局配置文件的kv配置。也可以通过Environment
对象的getProperty
方法获得kv配置。@MapperScan
配置要扫描并容器管理的包路径,这里我们精确到rds,以便使其内的Mapper
(见下文)与其他数据源隔离。sqlSessionFactoryRef
要定义key唯一的SqlSessionFactory
实例,否则同名的处理是后者被忽略。
类似地,另一个数据源ADS的配置如下:
@Configuration
@MapperScan(basePackages = AdsDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "adsSqlSessionFactory")
public class AdsDataSourceConfig {
static final String PACKAGE = "com.aliyun.xxx.repository.mybatis.ads";
@Value("${xxx_ads_url}")
private String dbUrl;
@Value("${xxx_ads_username}")
private String dbUser;
@Value("${xxx_ads_password}")
private String dbPassword;
@Bean(name = "adsDataSource")
public DataSource adsDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl(dbUrl);
dataSource.setUsername(dbUser);
dataSource.setPassword(dbPassword);
return dataSource;
}
@Bean(name = "adsTransactionManager")
public DataSourceTransactionManager adsTransactionManager(@Qualifier("adsDataSource") DataSource adsDataSource) {
return new DataSourceTransactionManager(adsDataSource);
}
@Bean(name = "adsSqlSessionFactory")
public SqlSessionFactory adsSqlSessionFactory(@Qualifier("adsDataSource") DataSource adsDataSource) throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(adsDataSource);
return sessionFactory.getObject();
}
}
Mapper
Mapper是mybatis的DAL层接口,其实现是由mybatis内部完成的,也就是说,我们只需要定义好接口即可完成CRUD。
com.aliyun.xxx.repository.mybatis.rds
包内的Mapper
只会用到RDS数据源。
package com.aliyun.xxx.repository.mybatis.rds;
@Mapper
public interface MetaMapper {
@SelectProvider(type = MetaSelectProvider.class, method = "xxxQueryById")
@Results(value ={
@Result(id=true, property="id",column="id",javaType=Long.class,jdbcType=JdbcType.BIGINT),
...
@Result(property="gmtCreate",column="gmt_create",javaType=Date.class,jdbcType=JdbcType.TIMESTAMP)})
List<XxxPojo> xxxQueryById(@Param("xxxId") String xxxId);
}
上述Mapper
定义了一个Select
方法,@SelectProvider
用于定义具体的SQL语句,@Results
用于定义具体的表字段与POJO属性的映射。
MetaSelectProvider
可以使用MyBatis的API完成SQL的拼装。
public class MetaSelectProvider {
private static final String xxxSQL = "id, ...,gmt_create";
public String xxxQueryById(Map<String, Object> parameter) {
org.apache.ibatis.jdbc.SQL sql = new org.apache.ibatis.jdbc.SQL();
sql.SELECT(xxxSQL).FROM("table_name").WHERE("biz_id=#{xxxId}");
return sql.toString();
}
}
DAO
@Repository
public class XxxDAO {
@Autowired
private MetaMapper metaMapper;
public List<XxxPojo> xxxQueryById(String xxxId) throws DataAccessException {
return metaMapper.xxxQueryById(xxxId);
}
}
SpringBootApplication
Spring Boot的入口类定义如下:
@SpringBootApplication
@PropertySource("file:/opt/xxx/xxx.properties")
public class XxxApplication {
public static void main(String[] args) {
SpringApplication.run(XxxApplication.class, args);
}
}
测试类
使用Spring的上下文,完成单元测试:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = XxxApplication.class)
public class TestXxxDAO {
private static final Logger logger = LogManager.getLogger(RelevanceResource.class);
@Autowired
private XxxDAO dao;
@Test
public void testXxxById() {
String xxxId = "C00018";
List<XxxPojo> list = dao.xxxQueryById(xxxId);
Assert.assertNotNull(list);
logger.info(...);
}
}
时间: 2024-09-21 19:25:45