springBoot系列之十五-----Mybatis和多数据原配置

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

开始吧:

第一步:

添加pom.xml依赖。

 
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.1.0


 
 
       mysql
        mysql-connector-java
        5.1.47
 


 
      com.alibaba
      druid-spring-boot-starter
       1.1.10
 

在配置 mysql 数据库的依赖的时候尽量配置上你的数据库的版本号  防止不必要的错误。

第二步:配置数据库的基本信息

pring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=qq123456
spring.datasource.url=jdbc:mysql://localhost:3306/account_a?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=GMT%2B8&useSSL=false

第三步:Mapper的接口

/**
 *
 * @author
 */
public interface UserMapper {

    public List  findAllUser();

}

所有的Mapper的接口必须被spring扫描到才会生效。有两种种方法解决;

方式一:在springBoot启动类上添加注解配置包扫描路径

@MapperScan(basePackages = "com.ja.spring_boot_dome.mybatis.Mapper")

这样 这个包下面的全部mapper接口都会被扫描到。

还可以配置多个路径扫描,以下面这种形式为例。

@MapperScan({"com.kfit.demo","com.kfit.user"}) 

方式二:在mapper接口上加注解@Mapper

@Mapper
public interface UserMapper {
    public List  findAllUser();
}

这种方式呢比较繁琐 ,因为每个接口都需加注解。看个人喜欢什么形式了。

第四步:mybatis 对于sql的编写 也有两种格式:

方式一:xml格式:

例如下面的userMapper.xml





这个xml存放位置也有要求的,默认支持在resources目录下,创建和mapper接口类一样的包路径

例如:我的mapper 接口在main/java/.com.ja.mapper

    userMapper.xml 的存放路径  resources/com.ja.mapper

这样做的目的是maven打包时能找到这些xml文件,一起打包。

如果你想创建那么多的目录,例如:你只在resources下面创建一个mapper目录来存放xml.你可以在配置文件中指定这个目录。

mybatis.mapper-locations=classpath:mapper/*.xml

  方式二:注解方式。

/**
 *
 * @author
 */
@Mapper
public interface UserMapper {
    
    @Select("select * from user")
    public List  findAllUser();
    
    
    
}

可以在方法上,加@Select ,@Update,@Inster,@Delect   来对应相关的操作。

具体的可以查阅相关的资料。

 

mybatis多数据源配置:

在项目中也会有可能用到多个数据库来访问,所以要掌握多数据源的配置也是必要的。

#=========================Mybatis数据源一================
spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.one.username=root
spring.datasource.one.password=qq123456
spring.datasource.one.url=jdbc:mysql://localhost:3306/account_a?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=GMT%2B8&useSSL=false


#=========================Mybatis数据源二================
spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.two.username=root
spring.datasource.two.password=qq123456
spring.datasource.two.url=jdbc:mysql://localhost:3306/account_b?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=GMT%2B8&useSSL=false

sql文件:account_a数据库

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for account_info
-- ----------------------------
DROP TABLE IF EXISTS `account_info`;
CREATE TABLE `account_info`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `account_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '户 主姓名',
  `account_no` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '银行 卡号',
  `account_password` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '帐户密码',
  `account_balance` double NULL DEFAULT NULL COMMENT '帐户余额',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of account_info
-- ----------------------------
INSERT INTO `account_info` VALUES (2, '张三的账户', '1', '', 1000);

sql文件:account_b数据库

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for account_info
-- ----------------------------
DROP TABLE IF EXISTS `account_info`;
CREATE TABLE `account_info`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `account_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '户 主姓名',
  `account_no` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '银行 卡号',
  `account_password` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '帐户密码',
  `account_balance` double NULL DEFAULT NULL COMMENT '帐户余额',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of account_info
-- ----------------------------
INSERT INTO `account_info` VALUES (3, '李四的账户', '2', NULL, 0);

配置DataSource 数据源类:

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @author xingChunWei
 */
@Configuration
public class DataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.one")
    DataSource dsOne(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.two")
    DataSource dsTwo(){
        return DruidDataSourceBuilder.create().build();
    }
}

配置MybatisConfig 数据源一:

package com.ja.spring_boot_dome.mybatis.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @author xingChunWei
 */
@Configuration
//下面配置的需要扫描的Mapper 文件路径 
@MapperScan(basePackages = "com.ja.spring_boot_dome.mybatis.mapper1"
        ,sqlSessionFactoryRef = "sqlSessionFactory1",sqlSessionTemplateRef = "sqlSessionTemplate1")
public class MybatisConfigOne {

    @Resource(name = "dsOne")
    DataSource dsOne;

    @Bean
    SqlSessionFactory sqlSessionFactory1() {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        try {
            sessionFactoryBean.setDataSource(dsOne);
            return sessionFactoryBean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Bean
    SqlSessionTemplate sqlSessionTemplate1() {

        return new SqlSessionTemplate(sqlSessionFactory1());

    }
}

配置MybatisConfig 数据源二:

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @author xingChunWei
 */
@Configuration
//下面配置的需要扫描的Mapper 文件路径 
@MapperScan(basePackages = "com.ja.spring_boot_dome.mybatis.mapper2"
        ,sqlSessionFactoryRef = "sqlSessionFactory2",sqlSessionTemplateRef = "sqlSessionTemplate2")
public class MybatisConfigTwo {

    @Resource(name = "dsTwo")
    DataSource dsTwo;

    @Bean
    SqlSessionFactory sqlSessionFactory2() {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        try {
            sessionFactoryBean.setDataSource(dsTwo);
            return sessionFactoryBean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Bean
    SqlSessionTemplate sqlSessionTemplate2() {

        return new SqlSessionTemplate(sqlSessionFactory2());

    }
}

实体类:

@Data
public class accountInfo {


    private Integer id;
    private String account_name;

    private String account_no;
    private String account_password;
    private double account_balance;
}

Mapper 文件:

springBoot系列之十五-----Mybatis和多数据原配置_第1张图片

mapper1文件:

/**
 *
 * @author
 */
@Mapper
public interface AccountMapper1 {

    @Select("select * from account_info")
    public List  findAllUser();



}




mapper2文件:


/**
 *
 * @author
 */
@Mapper
public interface AccountMapper2 {

    @Select("select * from account_info")
    public List  findAllUser();



}

测试结果:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootDomeApplicationTests {


    @Autowired
    AccountMapper1 accountMapper1;

    @Autowired
    AccountMapper2 accountMapper2;
    @Test
    public void contextLoads() {

        List allAccountInfo = accountMapper1.findAllUser();
        System.out.println(allAccountInfo);

        List allUser = accountMapper2.findAllUser();
        System.out.println(allUser);
    }

你可能感兴趣的:(springBoot系列之十五-----Mybatis和多数据原配置)