近期遇到特殊场景需要指定数据源进行数据新增查询操作。代码如下:
/**
* 数据源配置
*
* @author lyc
* @date 2022/03/10
*/
@Component
public class TempDbSource {
//数据库连接相关配置 说明:项目中使用的Druid数据源所以需要这些配置信息
@Value("${lyc.datasource.url}")
private String url;
@Value("${lyc.datasource.type}")
private String type;
@Value("${lyc.datasource.driver-class-name}")
private String driverClass;
@Value("${lyc.datasource.username}")
private String username;
@Value("${lyc.datasource.password}")
private String password;
@Value("${lyc.datasource.pwd-public-key}")
private String pwdPublicKey;
private SqlSessionTemplate sqlSessionTemplate;
@PostConstruct
public void init() throws Exception {
DruidDataSource slaveDataSource = new DruidDataSource();
slaveDataSource.setUrl(url);
slaveDataSource.setDbType(type);
slaveDataSource.setFilters("config");
slaveDataSource.setDriverClassName(driverClass);
slaveDataSource.setUsername(username);
slaveDataSource.setPassword(password);
slaveDataSource.setConnectionProperties("config.decrypt=true;config.decrypt.key=" + pwdPublicKey);
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
// 扫描相关mapper文件
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// 说明:mapper文件地址,可以添加多个
// Resource[] mapperLocations = ArrayUtil.addAll(resolver.getResources("classpath*:mapper/com/lyc/BizMapper.xml"),resolver.getResources("classpath*:mapper/com/lyc/BizMapper2.xml"));
Resource[] mapperLocations = ArrayUtil.addAll(resolver.getResources("classpath*:mapper/com/lyc/BizMapper.xml"));
sqlSessionFactoryBean.setMapperLocations(mapperLocations);
// 调用dataSource
sqlSessionFactoryBean.setDataSource(slaveDataSource);
// 映射实体类 说明:com.lyc.entity 对应实体类的包路径
sqlSessionFactoryBean.setTypeAliasesPackage("com.lyc.entity");
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
}
public SqlSessionTemplate getSqlSessionTemplate() {
return sqlSessionTemplate;
}
}
业务service及实现:
/**
* Service 接口
*
* @author lyc
* @date 2022/03/10
*/
public interface BizService {
/**
* 查询列表
*
* @param queryVo
* @return
*/
List<ModuleBean> listTestDatas(QueryVo queryVo);
/**
* 批量保存数据
*
* @param list
*/
void insertBatch(List<ModuleBean> list);
}
/**
* serviceImpl
*
* @author lyc
* @date 2022/03/10
*/
@Service
public class BizServiceImpl implements BizService {
@Autowired
private TempDbSource tempDbSource;**//这里就是自己加的数据源配置类**
@Override
public List<ModuleBean> listTestDatas(QueryVo queryVo) {
//这里的com.lyc.dao.BizDao.listTestDatas就是BizDao的包路径及对应要调用的接口方法
return tempDbSource.getSqlSessionTemplate().selectList("com.lyc.dao.BizDao.listTestDatas", queryVo);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void insertBatch(List<ModuleBean> list) {
tempDbSource.getSqlSessionTemplate().insert("com.lyc.dao.BizDao.insertBatch", list);
}
}
BizDao接口:
/**
* Dao
*
* @author lyc
* @date 2022/03/10
*/
public interface BizDao {
/**
* 查询列表
*
* @param queryVo
* @return
*/
List<ModuleBean> listTestDatas(QueryVo queryVo);
/**
* 批量保存数据
*
* @param list
*/
void insertBatch(List<ModuleBean> list);
}
对应的BizMapper.xml文件(这个文件就是数据源配置类中扫描的mapper文件):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lyc.BizDao">
<resultMap id="BaseResultMap" type="com.lyc.entity.ModuleBean"/>
<!--查询列表-->
<select id="listTestDatas" parameterType="com.lyc.vo.QueryVo" resultMap="BaseResultMap">
SELECT
id,name,age
FROM
test_module_bean_table
<where>
<if test="name!= null and name!= '' ">
AND name=#{name}
</if>
</where>
</select>
<!--批量保存数据-->
<insert id="insertBatch" parameterType="com.lyc.entity.ModuleBean">
insert into test_module_bean_table(name,age,create_time,create_by) values
<foreach collection="list" item="item" separator=",">
(#{item.name},#{item.age},now(),'sys_test')
</foreach>
</insert>
</mapper>
ArrayUtil工具类的方法:
public static <T> T[] addAll(T[]... arrays) {
if (arrays.length == 1) {
return arrays[0];
}
int length = 0;
for (T[] array : arrays) {
if (array == null) {
continue;
}
length += array.length;
}
T[] result = newArray(arrays.getClass().getComponentType().getComponentType(), length);
length = 0;
for (T[] array : arrays) {
if (array == null) {
continue;
}
System.arraycopy(array, 0, result, length, array.length);
length += array.length;
}
return result;
}
public static <T> T[] newArray(Class<?> componentType, int newSize) {
return (T[]) Array.newInstance(componentType, newSize);
}
至此使用BizService调用接口方法就可以通过指定的数据源操作数据了。