欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot 2.1.X学习之路——整合mybatis

程序员文章站 2022-05-22 09:02:45
...

项目结构

实体类
(此处省略建表、造数据以及实体类创建过程)
spring boot 2.1.X学习之路——整合mybatis
spring boot 2.1.X学习之路——整合mybatis

pom.xml配置

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

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.16</version>
            </dependency>

application.yml添加数据库配置信息

spring:
  application:
    name: system-service
  datasource:
    url: jdbc:mysql://localhost:3306/yml?serverTimezone=UTC
    username: root
    password: 123456


mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  configuration:
    map-underscore-to-camel-case: true

编写dao层接口与映射文件

SystemUserDao.java

@Mapper
public interface SystemUserDao {
    SystemUserDO queryUser();
}

UserMapper.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="com.dream.dao.SystemUserDao">
    <select id="queryUser" resultType="com.dream.system.user.SystemUserDO">
        select * from t_sys_user limit 1
    </select>
</mapper>

主函数入口需添加对Mapper的扫描配置

SystemApplication.java

@SpringBootApplication
@MapperScan(value = {"com.dream.dao"})
public class SystemApplication {

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

注意事项

  1. spring boot整合mybatis是dao层接口的注解是@Mapper
  2. 主函数需要添加对dao层文件的扫描
  3. mybatis的相关配置可以参照官网mybatis配置

运行测试

此处直接走测试类进行测试
spring boot 2.1.X学习之路——整合mybatis