Spring Boot入門サンプル-152-mybatis-multi-source統合mybatis多データソースMulti Source


Spring Boot入門サンプル-152-mybatis-multi-source統合mybatis多データソースMulti Source
システムが複数に分割されると、ユーザテーブルと注文書テーブルが別のデータベースにあるようになります.本デモでは、マルチデータソースMulti Sourceをどのようにmybatisで統合するかを実証しています.
前言
本Spring Boot入門見本準備作業参考:
  • Spring Boot入門例-001-JavaとMavenの設置配置
  • Spring Boot入門例-003-indeaインストール構成とプラグイン
  • Spring Boot入門例-005-どうやって
  • を実行しますか?
    pox.xml
    必要な依存性は以下の通りです.具体的にはこの項目のpox.xmlを参照してください.
            
                org.springframework.boot
                spring-boot-starter-web
            
            
                org.springframework.boot
                spring-boot-starter-data-jpa
            
            
                mysql
                mysql-connector-java
            
            
                org.projectlombok
                lombok
                true
            
    
    設定ファイル
    データテーブル構造はルートディレクトリ下のdb.sqlを参照してください.
    USE springbootdemo;
    DROP TABLE IF EXISTS `student`;
    CREATE TABLE `student` (
      `id` varchar(255) NOT NULL,
      `name` varchar(255) NOT NULL,
      `age` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    USE springbootdemo1;
    DROP TABLE IF EXISTS `tbl_order`;
    CREATE TABLE `tbl_order` (
      `id` varchar(255) NOT NULL,
      `student_id` varchar(255) NOT NULL,
      `sn` varchar(255) NOT NULL,
      `amount` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    resoures/appration.ymlの設定内容
    spring:
      datasource:
        user:
          driverClassName: com.mysql.jdbc.Driver
          jdbc-url: jdbc:mysql://localhost:3306/springbootdemo?useUnicode=true&characterEncoding=utf-8&useSSL=false&useAffectedRows=true
          username: root
          password: root
        order:
          driverClassName: com.mysql.jdbc.Driver
          jdbc-url: jdbc:mysql://localhost:3306/springbootdemo1?useUnicode=true&characterEncoding=utf-8&useSSL=false&useAffectedRows=true
          username: root
          password: root
    
    mybatis:
      configuration:
        map-underscore-to-camel-case: true
    
    コード解析
    このプロジェクトには多くのカタログがあります.それぞれ次のように説明します.
  • controllerディレクトリは、コントローラファイル
  • である.
  • entityディレクトリは、テーブル内のフィールド
  • に対応しています.
  • daoディレクトリデータアクセスオブジェクト
  • サービスインターフェースディレクトリ
  • service/implはサービスインターフェースの具体的な実現ディレクトリ
  • である.
  • utilはツールカタログです.分布式id雪花アルゴリズム
  • を加入します.
    以上の説明はSpring Boot入門の例-040-JPAを参考にして自動的にデータベース中のデータを読み取ります.
    UserConfig.javaプロファイル
    @Configuration
    @MapperScan(basePackages = "com.funsonli.springbootdemo152mybatismultisource.mapper.user", sqlSessionTemplateRef = "userSqlSessionTemplate")
    public class UserConfig {
    
        @Bean(name = "userDataSource")
        @ConfigurationProperties(prefix = "spring.datasource.user")
        @Primary
        public DataSource testDataSource() {
            return DataSourceBuilder.create().build();
        }
    
        @Bean(name = "userSqlSessionFactory")
        @Primary
        public SqlSessionFactory userSqlSessionFactory(@Qualifier("userDataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/user/*.xml"));
            return bean.getObject();
        }
    
        @Bean(name = "userTransactionManager")
        @Primary
        public DataSourceTransactionManager userTransactionManager(@Qualifier("userDataSource") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }
    
        @Bean(name = "userSqlSessionTemplate")
        @Primary
        public SqlSessionTemplate userSqlSessionTemplate(@Qualifier("userSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }
    
    
    Order Config注文書があるデータソースの配置
    @Configuration
    @MapperScan(basePackages = "com.funsonli.springbootdemo152mybatismultisource.mapper.order", sqlSessionTemplateRef = "orderSqlSessionTemplate")
    public class OrderConfig {
    
        @Bean(name = "orderDataSource")
        @ConfigurationProperties(prefix = "spring.datasource.order")
        public DataSource orderDataSource() {
            return DataSourceBuilder.create().build();
        }
    
        @Bean(name = "orderSqlSessionFactory")
        public SqlSessionFactory orderSqlSessionFactory(@Qualifier("orderDataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/order/*.xml"));
            return bean.getObject();
        }
    
        @Bean(name = "orderTransactionManager")
        public DataSourceTransactionManager orderTransactionManager(@Qualifier("orderDataSource") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }
    
        @Bean(name = "orderSqlSessionTemplate")
        public SqlSessionTemplate orderSqlSessionTemplate(@Qualifier("orderSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }
    
    
    StudentController.javaコントローラは、service操作データベースを呼び出します.
    @Slf4j
    @RestController
    @RequestMapping("/student")
    public class StudentController {
    
        @Autowired
        StudentService studentService;
    
        @Autowired
        OrderService orderService;
    
        @GetMapping({"", "/", "index"})
        public String index() {
            return studentService.index().toString() + " | " + studentService.index().toString();
        }
    
        @GetMapping("/add/{name}/{age}")
        public String add(HttpServletRequest request, @PathVariable String name, @PathVariable Integer age) {
            Student model = new Student();
            model.setName(name);
            model.setAge(age);
    
            int res = studentService.save(model);
            return String.valueOf(res);
        }
    
        @GetMapping("/order/{studentId}/{amount}")
        public String order(HttpServletRequest request, @PathVariable String studentId, @PathVariable Integer amount) {
            Order model = new Order();
            model.setStudentId(studentId);
            model.setSn(UUID.randomUUID().toString().replace("-", ""));
            model.setAmount(amount);
    
            int i = orderService.save(model);
            return "ok";
        }
    }
    
    
    実行
    クリックして実行
             
          http://localhost:8080/student/add/funson/30
    1
          http://localhost:8080/student/add/zhonghua/28
    1
    
             
          http://localhost:8080/student/order/sssss/30
    ok
          http://localhost:8080/student/order/ddddd/28
    ok
    
          http://localhost:8080/student/
    [Student(id=381159203135426560, name=funson, age=30), Student(id=381159203135926560, name=zhonghua, age=28)), Order(id=396289506464108544, studentId=aa, sn=9f53a28efe50461e97700c0f13af414f, amount=123)]
    
                      
    
    参照
  • Spring Boot入門サンプルソースコードアドレスhttps://github.com/funsonli/spring-boot-demo
  • Bootanソースコードアドレスhttps://github.com/funsonli/bootan
  • 付属する
    本Spring Boot入門の見本とサンプルコードが好きなら、素敵なスターを注文してください.