以前都用JPA,配置多元数据库稍微麻烦那面一点点,这几天看了下年轻人的Java代码,发现Mybatis用得比较多了,而且还有比较好用的三方库,配置多元数据库,相对简单,在此记录下。方便以后使用。
Maven导入:
XML
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
在yml文件中配置,官方只给出了yml。properties没有提,但看了yml后,发现的确比properties要简洁好用多了。
bash
spring:
datasource:
dynamic:
primary: mysql
datasource:
mysql:
url: jdbc:mysql://127.0.0.1:3306/XXX?characterEncoding=utf-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
dm7:
url: jdbc:dm://127.0.0.1/XXX?characterEncoding=utf-8&useSSL=false
username: SYSDBA
password: SYSDBA
driver-class-name: dm.jdbc.driver.DmDriver
这里有点要注意的primary必须指定一个,不然项目启动后会报错。
使用就相当简单了,用注解就可以了。下面我用jdbctemplate来调用下。
MySQLTest.java
java
package cn.demo.test;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@Component
@DS("mysql")
public class MySQLTest {
@Autowired
private JdbcTemplate jdbcTemplate;
public List<Map<String, Object>> test(){
return jdbcTemplate.queryForList("select * from XXX.XXX");
}
}
DMTest.java
java
package cn.demo.test;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@Component
@DS("dm7")
public class DMTest {
@Autowired
private JdbcTemplate jdbcTemplate;
public List<Map<String, Object>> test(){
return jdbcTemplate.queryForList("select * from XXX.XXX");
}
}
TestMain.java
java
package cn.demo;
import cn.demo.test.DMTest;
import cn.demo.test.MySQLTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TestMain implements CommandLineRunner {
@Autowired
DMTest dmTest;
@Autowired
MySQLTest mySQLTest;
public static void main(String[] args) {
SpringApplication.run(TestMain.class, args);
}
public void run(String... args) throws Exception {
System.out.println(dmTest.test());
System.out.println(mySQLTest.test());
}
}
启动后打印这个,就是成功了
源码打包下载地址:
Java/dynamic-datasource-demo at master · fengfanchen/Java · GitHub