SpringBoot 整合MyBatis

整合MyBatis

官方文档:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

Maven仓库地址:https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter/2.1.3

SpringBoot 整合MyBatis_第1张图片

整合测试

  1. 导入 MyBatis 所需要的依赖(方式一)

    <dependency>
        <groupId>org.mybatis.spring.bootgroupId>
        <artifactId>mybatis-spring-boot-starterartifactId>
        <version>2.1.3version>
    dependency>
    

    方式二:
    SpringBoot 整合MyBatis_第2张图片

  2. 配置数据库连接信息(不变)

    spring:
      datasource:
        username: root
        password: 123456
        #?serverTimezone=UTC解决时区的报错
        url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource
    
        #Spring Boot 默认是不注入这些属性值的,需要自己绑定
        #druid 数据源专有配置
        initialSize: 5
        minIdle: 5
        maxActive: 20
        maxWait: 60000
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
    
        #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
        #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
        #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
        filters: stat,wall,log4j
        maxPoolPreparedStatementPerConnectionSize: 20
        useGlobalDataSourceStat: true
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
        
      #properties方式
     spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
     spring.datasource.url=jdbc:mysql://localhost:3306/db_warehouse?serverTimezone=UTC
     spring.datasource.username=root
     spring.datasource.password=123456
     #mybatis
     #指定sql映射文件位置
     mybatis.mapper-locations=classpath:mapper/*.xml
     #开启驼峰命名规则
     mybatis.configuration.map-underscore-to-camel-case=true
     #开启日志功能
     mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
     #给实体起别名
     mybatis.type-aliases-package=com.liming.pojo
    
  3. 创建实体类,导入 Lombok!

    User.java

    package nuc.ss.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
        private int id;
        private String name;
        private String pwd;
    }
    
  4. 创建mapper目录以及对应的 Mapper 接口

    UserMapper.java

    package nuc.ss.mapper;
    
    import nuc.ss.pojo.User;
    import org.apache.ibatis.annotations.Mapper;
    import org.springframework.stereotype.Repository;
    
    import java.util.List;
    
    
     //或在启动类上添加@MapperScan(basePackages = "com.liming.mapper")
    @Mapper// 这个注解表示了这是一个 mybatis 的 mapper 类
    public interface UserMapper {
    
        List<User> queryUserList();
    
        User queryUserById(int id);
    
        int addUser(User user);
    
        int updateUser(User user);
    
        int deleteUser(int id);
    }
    
  5. 对应的Mapper映射文件

    UserMapper.xml

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="nuc.ss.mapper.UserMapper">
        
        <select id="queryUserList" resultType="User">
            select * from mybatis.user;
        select>
    
        <select id="queryUserById" resultType="User">
            select * from mybatis.user where id = #{id};
        select>
    
        <insert id="addUser" parameterType="User">
            insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
        insert>
    
        <update id="updateUser" parameterType="User">
            update mybatis.user set name=#{name},pwd = #{pwd} where id = #{id};
        update>
    
        <delete id="deleteUser" parameterType="int">
            delete from mybatis.user where id = #{id}
        delete>
    mapper>
    
  6. 编写部门的 UserController 进行测试!

    @RestController
    public class UserController {
        @Autowired
        private UserMapper userMapper;
    
        @GetMapping("/queryUserList")
        public List<User> queryUserList() {
            List<User> userList = userMapper.queryUserList();
    
            for (User user : userList) {
                System.out.println(user);
            }
    
            return userList;
        }
        
         //添加一个用户
        @GetMapping("/addUser")
        public String addUser() {
            userMapper.addUser(new User(7,"阿毛","123456"));
            return "ok";
        }
    
        //修改一个用户
        @GetMapping("/updateUser")
        public String updateUser() {
            userMapper.updateUser(new User(7,"阿毛","123456"));
            return "ok";
        }
    
        @GetMapping("/deleteUser")
        public String deleteUser() {
            userMapper.deleteUser(7);
    
            return "ok";
        }
    }
    

启动项目访问进行测试!

你可能感兴趣的:(SpringBoot,spring,boot,mybatis,后端)