在开发过程中,遇到了需要集成两个mysql和taos库的情况,根据多方资料配置成功,并记录一下。集成使用的是mybatis-plus-dynamic。
首先pom文件中需要支持多数据源的jar包
<!-- mybatis-plus配置不同数据源 需要引入的包 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.6.0</version>
</dependency>
引用taos库的jar包
<dependency>
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>2.0.38</version>
</dependency>
配置yml
spring:
application:
name: server
datasource:
dynamic:
#设置默认数据库源
primary: mysql1
#严格匹配数据源,默认为false,true未匹配到指定数据库时抛异常,false使用默认数据源
strict: false
datasource:
#数据源1
mysql1:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mysql1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2b8
username: root
password: 1
#mysql2地址
mysql2:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mysql2?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2b8
username: root
password: 1
#时序库
taos:
driver-class-name: com.taosdata.jdbc.TSDBDriver
url: jdbc:TAOS://127.0.0.1:6030/box?charset=UTF-8&locale=en_US.UTF-8
username: root
password: 1
mybatis-plus:
mapper-locations: classpath*:mapper/**/*.xml
global-config:
db-config:
logic-delete-value: 10
logic-not-delete-value: 20
logic-delete-field: delFlag
table-underline: true
id-type: assign_uuid
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
auto-mapping-unknown-column-behavior: WARNING
call-setters-on-nulls: false
cache-enabled: true
不同数据源使用
@DS注解进行配置选择数据源,并且可以在类上进行配置。
@DS("mysql1")
@Repository("InfoMapper")
public interface InfoMapper extends BaseMapper<InfoEntity> {
List<InfoEntity> queryALl();
}
@DS("mysql2")
@Repository("JobMapper")
public interface JobMapper extends BaseMapper<JobInfoEntity> {
}
taos库的使用
@DS("taos")
@Mapper
public interface HistoryMapper extends BaseMapper {
List<Object> historyData(@Param("tableName") String tableName, @Param("condition") String condition);
}
遇到的问题
如果出现调用的mysql的mapper却报错是taos的mapper。说明taos的mapper有错误。返回结果一定的resultMap的。
<resultMap id="historyDTO" type="com.HistoryDTO">
<result column="ts" property="times" />
<result column="deviceid" property="deviceId" />
<result column="boxid" property="boxId" />
<result column="ticketno" property="ticketNo" />
</resultMap>
<select id="historyData" resultMap="historyDTO">
select * from #{tableName} order by ts desc limit 1;
</select>
参考资料:SpringBoot+Mybatis-Plus多数据源使用_双数据源mybatisplus_懒虫虫~的博客-CSDN博客