springbootのデフォルトの設定では、構成データが便利なことが多いですが、複数のデータソースには、もう少し複雑に配置されたことを一つの特徴などよりも大きくなります。
送信元アドレス:https://github.com/jinjunzhu/spring-boot-mybatis.git
1.統合MyBatisの設定し、A単一のデータソース、のみ、以下のステップ
1)構成データベースに接続されました
spring.datasource.url=jdbc:mysql://localhost:3306/zhujinjun?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=test
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
2)構成MyBatisのプロフィール
3)書き込みマッパーファイル
2.統合MyBatisの設定し、複数のデータソースには、より多くの設定が必要
1)コンフィギュレーションデータソース
######primary#############
datasource.first.jdbc-url=jdbc:mysql://localhost:3306/jinjunzhu?serverTimezone=UTC&characterEncoding=utf-8
datasource.first.username=root
datasource.first.password=123456
datasource.first.driver-class-name=com.mysql.cj.jdbc.Driver
######secondary#############
datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/jinjunzhu1?serverTimezone=UTC&characterEncoding=utf-8
datasource.secondary.username=root
datasource.secondary.password=123456
datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
2)設定ファイルMyBatisの
最初のデータソースの場合
@Component("mybatisConfig")
@MapperScan(basePackages={"boot.repository.dao1"}, sqlSessionFactoryRef = "firstSqlSessionFactory")
public class MybatisConfig {
@Bean(name="firstDataSource")
@ConfigurationProperties(prefix="datasource.first")
@Primary
public DataSource firstDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "firstSqlSessionFactory")
public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis/mapper/mybatis-config.xml"));
return bean.getObject();
}
@Bean(name = "firstTransactionManager")
@Primary
public DataSourceTransactionManager firstTransactionManager(@Qualifier("firstDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "firstSqlSessionTemplate")
public SqlSessionTemplate firstSqlSessionTemplate(
@Qualifier("firstSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
//@Resource
//@Qualifier("firstSqlSessionTemplate")
//protected SqlSession firstSqlSession;
}
第二のデータ・ソースの
@Component("mybatisConfig1")
@MapperScan(basePackages={"boot.repository.dao2"}, sqlSessionFactoryRef = "secondSqlSessionFactory")
public class MybatisConfig1 {
@Bean(name="secondDataSource")
@ConfigurationProperties(prefix="datasource.secondary")
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondSqlSessionFactory")
public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis/mapper1/mybatis-config.xml"));
return bean.getObject();
}
@Bean(name = "secondTransactionManager")
public DataSourceTransactionManager secondTransactionManager(@Qualifier("secondDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "secondSqlSessionTemplate")
public SqlSessionTemplate secondSqlSessionTemplate(
@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
3)DAOクラスを作成し、ファイルへのマッパー
2から)次のように画像、異なるファイルとマッパークラスDAO格納ディレクトリ、ディレクトリ構造で見られます:
3.ユニットテスト
1)データソースのテストコード1:
@Test
public void testInsertEmployee(){
Employee employee = employeeService.getEmployee("lisi");
Assert.assertNull(employee);
Employee employee1 = new Employee();
employee1.setName("lisi");
employee1.setDepartment("4");
employee1.setNumber(2002950l);
employeeService.insertEmployee(employee1);
employee = employeeService.getEmployee("lisi");
Assert.assertNotNull(employee);
}
ログ、次のテスト出力クラスを開始します。
2)データソースのテストコード2
@Transactional(value="secondTransactionManager", rollbackFor=Exception.class)
public void testInsert() throws Exception{
Assert.assertNull(departmentService.getDepartment("jinjunzhu"));
Department department = new Department();
department.setLevel(2);
department.setName("jinjunzhu");
department.setId(2l);
departmentService.insertDepartment(department);
Department department1 = departmentService.getDepartment("jinjunzhu");
Assert.assertNotNull(department1);
}
テスト方法を実行し、ログは次のとおりです。
2つの検査方法以上のことから、テスト2番目のデータソースは、フィニッシュ後にロールバックをサポートするための試験方法に加えて、取引のノートにする必要があります。データソースMyBatisの@primary設定クラス1の増加のため。どのように達成するかの具体的な詳細は、研究されていません。
4.コードは三つのクラスのコントローラをサポート以下のように、テストするためのHTTPリクエストがあります。
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@RequestMapping("/{username}")
@ResponseBody
public String getPassword(@PathVariable String username) {
String passwd = userService.getUser(username).getPassword();
return passwd;
}
@RequestMapping("/saveUser/{username}")
@ResponseBody
public String saveUser(@PathVariable String username) {
User user = new User();
user.setUsername(username);
user.setPassword("111111");
try {
userService.insert(user);
return "success!";
} catch (Exception e) {
return "failure!";
}
}
}
@Controller
public class EmployeeController {
@Resource
private EmployeeService employeeService;
@RequestMapping("/employee/{name}")
@ResponseBody
public String getEmployeebyName(@PathVariable String name){
Employee employee = employeeService.getEmployee(name);
return null == employee?null:employee.getDepartment();
}
@RequestMapping("/employee/save/{name}/{department}/{number}")
@ResponseBody
public String saveEmployeebyName(@PathVariable String name,@PathVariable String department,@PathVariable Long number){
Employee employee = new Employee();
employee.setName(name);
employee.setDepartment(department);
employee.setNumber(number);
try{
employeeService.insertEmployee(employee);
return "success!";
}catch(Exception e){
return e.toString();
}
}
}
@Controller
public class DepartmentController {
Logger logger = LoggerFactory.getLogger(getClass());
@Resource
private DepartmentService departmentService;
@RequestMapping("/department/{name}")
@ResponseBody
public String getDepartment(@PathVariable String name){
Department department = departmentService.getDepartment(name);
return null == department?null:department.getName();
}
@RequestMapping("/department/save/{name}/{level}")
@ResponseBody
public void insertDepartment(@PathVariable String name,@PathVariable Integer level){
Department department = new Department();
department.setName(name);
department.setLevel(level);
try {
departmentService.insertDepartment(department);
} catch (Exception e) {
logger.error("保存部门失败:", e);
}
}
}
プロジェクトを開始した後、ブラウザの入力
http:// localhost:8080 /従業員/ jinjunzhu、返回部門
HTTP:// localhostを:8080 /従業員/保存/リージ/ department3 / 3は、正常に保存され
http:// localhost:8080 /部署/ department1、返回department1
http:// localhost:8080 /部門/ / department3 / 3の保存、保存成功
5.このプロジェクトは、バージョンを使用しています。
springboot:2.1.6.RELEASE
org.mybatis:2.0.1
MySQLのコネクタ:8.0.16
6.構成いくつかの注意事項:
1)@DependOnは:Beanが注釈の完了後に初期化されるような現在のビーンを初期化します
2)@MapperScan:一元管理BeanのばねによってマッパーMyBatisのようなクラスに以下の注意事項をパッケージ
3)@Primary:デフォルトの実装の優先
4)@Mapper:指定インターフェイスクラスはMyBatisのマッパーです