SpringBoot 整合Mybatis

一、SpringBoot 整合Mybatis

1、在创建SpringBoot 的项目时,选择JDBC、mysql,Mybatis,web的组件,或者自己手动在maven中添加库依赖:

       
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
   
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

2、在 application.yml(或aproperties)中添加相应的配置:

     注意 :配置 mybatis 的配置文件位置

server:
  port: 80

# Datasource
# 数据源基本配置
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/my_springboot?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT
    driver-class-name: com.mysql.cj.jdbc.Driver # com.mysql.jdbc.Driver

# 配置mybatis的配置文件的位置
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

# 打印sql:日志的方式
logging:
    level:
      # 路径指的是mybatis对应的方法接口所在的包。并不是mapper.xml所在的包
      cn.jq.springbootdemo.springbootdemo.dao : debug

3、新建一个model, dao类:

       在测试类中测试,所以 service 和controller就不写了

public class User {

    private long id;
    private String username;
    private String pazzword;
    private String sex;
    private int age;
    private Date birthday;
    ...
}
public interface UserDao {
    void add(User user);
    void delete(int id);
    void update(User user);
    User get(int id);
}

 

4、在 resources 下创建一个mybatis文件夹,在其下新建 mybatis-config.xml 全局配置mybatis文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

5、在 mybatis 下新建 mapper 文件夹,在其下新建 *.xml 映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.jq.springbootdemo.springbootdemo.dao.UserDao">

    <insert id="add">
        insert into t_user(username, pazzword, sex, age, birthday)
        values(#{username},#{pazzword},#{sex},#{age},#{birthday})
    </insert>
    <delete id="delete">
      delete from t_user where id = #{id}
    </delete>
    <update id="update">
        update t_user u set u.username = #{username}, u.sex = #{sex} where id = #{id}
    </update>
    <select id="get" resultType="cn.jq.springbootdemo.springbootdemo.model.User">
        select id, username, pazzword, sex, age, birthday from t_user where id = #{id}
    </select>
</mapper>

6、 在 启动类中 添加 @MapperScan 注解 扫描 mapper

配置mapper扫描,有两种方式:

  • 1. 是直接在UserDao类上添加@Mapper注解,弊端是所有的Mapper都要手动添加,要是有一个没添加就会报错。
  • 2. 直接在启动类上添加Mapper扫描,推荐使用。
@SpringBootApplication
@MapperScan(value = "cn.jq.springbootdemo.springbootdemo.dao")
public class SpringbootdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootdemoApplication.class, args);
    }

}

7、 在 测试类中 进行 CRUD

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootdemoApplicationTests {
    @Autowired
    private UserDao userDao;

    @Test
    public void contextLoads() throws SQLException {        
        System.out.println(userDao);

        // 新增
//        User user = new User();
//        user.setUsername("张三");
//        user.setPazzword("zhs123");
//        user.setSex("男");
//        user.setAge(20);
//        user.setBirthday(new Date());
//        userDao.add(user);

        // 删除
        //userDao.delete(1);

        // 修改
        User user = new User();
        user.setId(6);
        user.setUsername("张三6");
        user.setSex("女");
        userDao.update(user);
        
        // 查询
        user = userDao.get(6);
        System.out.println("getUser==" + user);
    }
}

   

  数据表:

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `pazzword` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `birthday` datetime DEFAULT NULL,
  `sex` varchar(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

   

二、SpringBoot 整合Mybatis

上面xml和mapper分离了,查看阅读不直观。这里方式二整合如下:不同点这里列出来。

1、在 application.yaml

这里不需要配置mybatis的配置文件的位置,放到pom中配置。

server:
  port: 8088

# 数据源基本配置
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/sbtdb1?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

2、引入依赖之后,在插件中加入:

    <build>
        <!--声明resource,避免打包时java目录下的XML文件被自动忽略掉-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
...
    </build>

3、UserMapper和xml

public interface UserMapper {

    List<User> listAll();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.example.mybatis.mapper.UserMapper">

    <select id="listAll" resultType="com.example.mybatis.pojo.User">
        select id,name,password from t_user
    </select>
</mapper>

4、测试

@SpringBootApplication
@MapperScan(basePackages ={"com.example.mybatis.mapper"})
public class MybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }

}
@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/list")
    public List<User> list(){
        List<User> list = userMapper.listAll();
        return list;
    }

}

 

三、SpringBoot 配置多数据源之Mybatis

1、在创建SpringBoot 的项目时,引入依赖,在插件中声明 .xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.13</version>
        </dependency>


    <build>
        <!--声明resource,避免打包时java目录下的XML文件被自动忽略掉-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
...
    </build>

2、在 application.aproperties中添加两个数据源的配置信息

server.port=8088
# 配置两个数据源
spring.datasource.dsone.url=jdbc:mysql://localhost:3306/sbtdb1?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT
spring.datasource.dsone.username=root
spring.datasource.dsone.password=123456
spring.datasource.dsone.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.dsone.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.dstwo.url=jdbc:mysql://localhost:3306/sbtdb2?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT
spring.datasource.dstwo.username=root
spring.datasource.dstwo.password=123456
spring.datasource.dstwo.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.dstwo.driver-class-name=com.mysql.cj.jdbc.Driver

3、在配置类中,定义两个DataSource Bean

@Configuration
public class DataSourceConfig {
    /**
     * 定义两个DataSource
     * 使用spring.datasource.dsone前缀的数据库配置去创建一个DataSource
     */
    @Bean("dsOne")
    @ConfigurationProperties(prefix = "spring.datasource.dsone")
    DataSource dsOne() {
        return DruidDataSourceBuilder.create().build();
    }

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

}

4、提供两个Bean,并配置数据源

@Configuration
@MapperScan(basePackages = "com.example.mybatis.mapper1",
        sqlSessionFactoryRef = "sqlSessionFactory1",
        sqlSessionTemplateRef = "sqlSessionTemplate1")
public class MyBatisConfigOne {
    @Resource(name = "dsOne")
    DataSource dsOne;

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

    @Bean
    SqlSessionTemplate sqlSessionTemplate1() {
        return new SqlSessionTemplate(sqlSessionFactory1());
    }
}
@Configuration
@MapperScan(basePackages = "com.example.mybatis.mapper2",
        sqlSessionFactoryRef = "sqlSessionFactory2",
        sqlSessionTemplateRef = "sqlSessionTemplate2")
public class MyBatisConfigTwo {
    @Resource(name = "dsTwo")
    DataSource dsTwo;

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

    @Bean
    SqlSessionTemplate sqlSessionTemplate2() {
        return new SqlSessionTemplate(sqlSessionFactory2());
    }
}

5、mapper创建(mapper1和mapper2根据业务去写)

public interface UserMapper1 {

    List<User> listAll();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.example.mybatis.mapper1.UserMapper1">

    <select id="listAll" resultType="com.example.mybatis.pojo.User">
        select id,name,password from t_user
    </select>
</mapper>

6、测试

@SpringBootApplication
public class MybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }

}
@RestController
public class UserController {

    @Autowired
    private UserMapper1 userMapper1;

    @Autowired
    private UserMapper2 userMapper2;

    @GetMapping("/list1")
    public List<User> list(){
        List<User> list = userMapper1.listAll();
        return list;
    }

    @GetMapping("/list2")
    public List<User> list2(){
        List<User> list = userMapper2.listAll();
        return list;
    }

}

   

在Spring Boot中,查看org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration类中,可以看到Spring Boot提供了两个Bean(一个SqlSessionFactory,一个sqlSessionTemplate)。

单数据源时,我们指明数据源配置信息,SpringBoot可自动为我们创建好这两个bean。

多数据源时,我们根据数据源配置信息,可以自已定义创建这两个bean。

有兴趣可以查看下源码。

 

参考文章:http://www.javaboy.org/2019/0407/mybatis-multi.html

ends ~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值