基于动态的数据源,查询表数据,这里操作的表示已知的表结构,实际上动态数据源的表结构都是需要再次动态获取表字段,才能操作。(下节数据动态读取和写入会详说)
@Api(value = "JdbcQueryController") @RestController public class JdbcQueryController { @Resource private DataSourceFactory dataSourceFactory ; @GetMapping("getList") public List<ConnectionEntity> getList (@RequestParam("id") Integer id){ String sql = "SELECT * FROM jm_connection WHERE state='1'" ; JdbcTemplate jdbcTemplate = dataSourceFactory.getById(id); List<ConnectionEntity> connectionEntities = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ConnectionEntity.class)); return connectionEntities ; } } 三、批量管理持久化数据源的配置信息,多了一步配置信息入库,和入库信息加载到容器,使用时动态获取。
1、库表Mapper结构存储配置信息的表结构,转换Mapper文件。
<mapper namespace="com.dynamic.add.mapper.ConnectionMapper"> <!-- 通用查询映射结果 --> <resultMap type="com.dynamic.add.entity.ConnectionEntity"> <id column="id" property="id" /> <result column="data_type_name" property="dataTypeName" /> <result column="driver_class_name" property="driverClassName" /> <result column="jdbc_url" property="jdbcUrl" /> <result column="user_name" property="userName" /> <result column="pass_word" property="passWord" /> <result column="create_time" property="createTime" /> <result column="update_time" property="updateTime" /> <result column="state" property="state" /> </resultMap> <select resultMap="BaseResultMap" > SELECT * FROM jm_connection WHERE state='1' </select> </mapper> 2、持久化管理测试数据源链接是否成功,可用的数据源链接,配置信息入库保存。
@Service public class ConnectionServiceImpl implements ConnectionService { @Resource private ConnectionMapper connectionMapper ; @Resource private JdbcConfig jdbcConfig ; @Resource private DataSourceFactory dataSourceFactory ; @Override public boolean testConnection(ConnectionEntity connectionEntity) { return jdbcConfig.getConnection(connectionEntity) !=null ; } @Override public boolean addConnection(ConnectionEntity connectionEntity) { Connection connection = jdbcConfig.getConnection(connectionEntity) ; if (connection !=null){ int addFlag = connectionMapper.insert(connectionEntity); if (addFlag > 0){ dataSourceFactory.addDataSource(connectionEntity) ; return true ; } } return false ; } } 3、动态加载容器工厂类中,添加一个初始化的方法,加载入库的数据源配置信息。
@Component public class DataSourceFactory { /** * 初始化 JDBC 链接API */ @PostConstruct public void init (){ List<ConnectionEntity> connectionList = connectionMapper.getAllList(); if (connectionList != null && connectionList.size()>0){ for (ConnectionEntity connectionEntity:connectionList) { Connection connection = jdbcConfig.getConnection(connectionEntity) ; if (connection != null){ DataSource dataSource = getDataSource(connectionEntity); dataSourceMap.put(connectionEntity.getId(),dataSource) ; } } } } } 四、源代码地址 GitHub·地址 https://github.com/cicadasmile/data-manage-parent GitEE·地址 https://gitee.com/cicadasmile/data-manage-parent