SpringBoot-整合MyBatis

1 - 整合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.1

 

1、导入 MyBatis 所需要的依赖

<!--myBatis,注意是非spring-boot官方的依赖-->
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>

2、在yaml全局配置文件里配置数据库连接信息(增加整合mybatis的配置信息)

# yaml配置文件
# 配置数据库访问用户
spring:
  datasource:
    username: root
    password: '101323'
    url: jdbc:mysql://localhost:3306/test?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

# 整合mybatis
mybatis:
  type-aliases-package: com.howie.pojo # 为mapper映射文件pojo起别名
  mapper-locations: 'classpath:mybatis/mapper/*.xml' # 注册所有映射文件

3、测试数据库是否连接成功!

@SpringBootTest
class Day03ApplicationTests {
    // DI注入数据源
    @Autowired
    private DataSource dataSource;
    @Test
    void contextLoads() throws SQLException {
        Connection connection = null;
        try {
            // 查看一下默认的数据源:class com.zaxxer.hikari.HikariDataSource
            System.out.println("debug ==> " + dataSource.getClass());
            // 获取数据库连接
            connection = dataSource.getConnection();
            System.out.println(connection);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(connection != null){
                // 关闭连接
                connection.close();
            }
        }
    }
}

4、创建实体类(User.java)

5、创建mapper目录以及对应的 Mapper 接口(package com.howie.mapper)

//@Mapper : 表示本类是一个 MyBatis 的 Mapper
@Mapper // 也表示Dao
@Repository
public interface UserMapper {
    List<User> getAllUser(); // 查询所有用户信息
    User getUserById(int id); // 根据id获取用户信息
    int addUser(User user); // 添加新用户
    int update(User user); // 更新用户信息
    int delete(int id); // 根据id删除用户信息
}

6、对应的Mapper映射文件(resources/mybatis/mapper/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.howie.mapper.UserMapper">
    <select id="getAllUser" resultType="User">
        select * from test.user
    </select>
    <!--根据id获取用户信息-->
    <select id="getUserById" parameterType="int" resultType="User">
        select * from test.user where id = #{id}
    </select>
    <!--添加新用户-->
    <insert id="addUser" parameterType="User">
        insert into test.user (id,name,password,perms) value (#{id},#{name},#{password},#{perms})
    </insert>
    <!--更新用户信息-->
    <update id="update" parameterType="User">
        update test.user set name=#{name},password=#{password},perms=#{perms} where id=#{id}
    </update>
    <!--根据id删除用户信息-->
    <delete id="delete" parameterType="int">
        delete from test.user where id=#{id}
    </delete>
</mapper>

7、maven配置资源过滤问题

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
    </resource>
</resources>

8、编写用户的 UserController 进行测试!

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @GetMapping(path = "/get_all_user")
    public List<User> getAllUser(){
        List<User> userList = userMapper.getAllUser();
        for(User user:userList){
            System.out.println(user);
        }
        return userList;
    }
}

2 - 测试

启动项目访问进行测试!

 

posted @ 2020-10-19 09:27  赖正华  阅读(77)  评论(0编辑  收藏  举报