关于springboot:springboot中使用mybatis并进行测试

6次阅读

共计 5032 个字符,预计需要花费 13 分钟才能阅读完成。

1. pom.xml

具体 pom.xml 文件参考 blogger 源码

其中 h2 的 scope 能够是 test。

2. springboot 应用 mybatis 进行数据库操作

应用 mybatis 时,须要 org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.3[compile] 依赖。

而后创立一个接口,应用 @Mapper 标记,mybatis 会搜寻此标记,把这个接口解析为数据库操作接口。

package com.ws.product.blogger.dao;

import com.ws.product.blogger.dao.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;

@Mapper     // mybatis 用于发现 mapper 接口
@Component  // 能够省略。次要是为了在 IDEA 里 UserDaoTest 中 @Autowired 时不报错
public interface UserDao {User getById(int id);
    User getByUsername(String username);
    // 应用 java bean 传递多个参数,在 xml 中能够间接应用 bean 的 property name,即 #{username}
    int insert(User user);
    int delete(int id);
    // 两个参数,第二个参数是 java bean,应用的时候须要应用 #{user.username}
    int update(int id, User user);
}

User是一个 POJO,用来保留数据库中的数据:

package com.ws.product.blogger.dao.pojo;
import lombok.Data;
@Data
public class User {
    private int id;
    private String username;
    private String password;
}

而后在 src/main/resources 目录下新建 mapper 目录,再新建 UserDao.xml 文件,具体的 SQL 语句就写在这里。这个文件在哪里无所谓,之后通过 application.yml 配置文件中的 mybatis.mapper-locations: classpath:mapper/*.xml 属性找到这个文件。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ws.product.blogger.dao.UserDao"><!--namespace 是 java interface 和 xml 的匹配关系 -->
    <resultMap id="UserMap" type="com.ws.product.blogger.dao.pojo.User">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="username" property="username" jdbcType="VARCHAR"/>
        <result column="password" property="password" jdbcType="VARCHAR"/>
    </resultMap>

    <select id="getById" resultMap="UserMap">
        select * from t_user where id = #{id}
    </select>

    <select id="getByUsername" resultMap="UserMap">
        select * from t_user where username = #{username}
    </select>

    <insert id="insert" parameterType="com.ws.product.blogger.dao.pojo.User">
        insert into t_user (username, password) values (#{username}, #{password} )
    </insert>

    <delete id="delete">
        delete from t_user where id = #{id}
    </delete>

    <update id="update">
        update t_user
        <set>
            <if test="user.username != null">username = #{user.username},</if>
            <if test="user.password != null">password = #{user.password}</if>
        </set>
        where id = #{id}
    </update>
</mapper>

这样,mybatis 就具备了操作数据库的能力。对于独自一个 DAO 模块来说,这曾经足够了。如果想要真正执行数据库操作,须要新建一个 main 函数,应用 @SpringBootApplication 标记,application.yml 中配置 spring.datasource.url, username, password, driver-class-name 属性,这会主动生成一个 sqlSession,mybatis 会应用这个 sqlSession 操作数据库。不要忘了,application.yml 中还须要配置 mybatis.mapper-locations 属性。

3. 测试 mybatis

咱们应用 org.mybatis.spring.boot:mybatis-spring-boot-starter-test:2.1.3[test] 对 mybatis 进行测试,应用 H2 数据库的内存数据库,使得数据库测试能够反复执行。

首先创立一个空的 @SpringBootApplication 标记的类,用以加载所有应用到的 bean:

package com.ws.product.blogger.dao;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * 这是一个哨兵类,须要增加 @SpringBootApplication 注解,让 @MybatisTest 能够主动加载所需的类。必不可少
 */
@SpringBootApplication
public class MapperTestApplication {}

而后创立测试类,应用 @MybatisTest 标记:

package com.ws.product.blogger.dao;
import com.ws.product.blogger.dao.pojo.User;
import org.junit.jupiter.api.Test;
import org.mybatis.spring.boot.test.autoconfigure.MybatisTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.test.context.ActiveProfiles;
import static org.junit.jupiter.api.Assertions.assertEquals;

@MybatisTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)    // 应用实在的数据库,这里咱们应用 H2 内存数据库
// @Rollback(value = false)    // 默认为 true,数据库操作会回滚。改为 false 后,不会回滚
@ActiveProfiles("test")     // 应用 appplication-test.yml 作为配置文件
public class UserDaoTest {
    @Autowired
    private UserDao userDao;

    @Test
    public void test01() {User user = new User();
        user.setUsername("aaa");
        user.setPassword("aaa");
        int i = userDao.insert(user);
        assertEquals(1, i);
    }

    @Test
    public void test02() {User user = userDao.getByUsername("root");
        assertEquals(1, user.getId());
        assertEquals("root", user.getUsername());
        assertEquals("rootqqq", user.getPassword());
    }

    @Test
    public void test03() {User user = userDao.getById(1);
        assertEquals(1, user.getId());
        assertEquals("root", user.getUsername());
        assertEquals("rootqqq", user.getPassword());
    }

    @Test
    public void test04() {int i = userDao.delete(1);
        assertEquals(1, i);
    }

    @Test
    public void test05() {User user = new User();
        // user.setUsername("root");
        user.setPassword("root2");
        userDao.update(1, user);
        User user1 = userDao.getById(1);
        assertEquals("root", user1.getUsername());
        assertEquals("root2", user1.getPassword());
    }
}

创立配置文件src/test/resources/application-test.yml。spring.datasource.shcema 和 data 是建表语句和铺底数据语句

spring:
  datasource:
    url: jdbc:h2:mem:testdb
    username: sa
    password: sa
    driver-class-name: org.h2.Driver
    schema: classpath:sql/db/schema-h2.sql
    data: classpath:sql/db/data-h2.sql

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

schema-h2.sql 中内容为:

drop table if exists t_user;
create table t_user(
    id integer not null auto_increment,
    username varchar(100) not null,
    password varchar(200) not null,
    primary key (id)
);

data-h2.sql 中内容为:

insert into t_user values(1, 'root', 'rootqqq');

测试过程为:启动 UserDaoTest,依据@MybatisTest 找到 @SpringBootApplication 标记 ide 类,加载所有 bean,加载 application-test.yml。依据 spring.datasource 的配置创立 H2 内存数据库,并加载 schema-h2.sql 和 data-h2.sql 创立表和数。而后进行 mybatis 操作,生成 UserDao 实例,主动注入到 UserDaoTest 中,进行测试。

参考文档

  • Mybatis 传递多个参数的 4 种形式
  • MyBatis 传递多个参数
  • mybatis 中文教程
  • 动静 SQL
正文完
 0