MyBatis实现基本CRUD以及进行单元测试

32次阅读

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

整体项目结构

bean 代码

package bean;

public class Apply {
    private long id;
    private String sname;
    private String qq;
    private long enterTime;
    private String type;
    private String school;
    private long number;
    private String repLink;
    private String goal;

    @Override
    public String toString() {
        return "Apply{" +
                "id=" + id +
                ", sname='" + sname + '\'' +
                ", qq='" + qq + '\'' +
                ", enterTime=" + enterTime +
                ", type='" + type + '\'' +
                ", school='" + school + '\'' +
                ", number=" + number +
                ", repLink='" + repLink + '\'' +
                ", goal='" + goal + '\'' +
                '}';
    }

    public Apply() {}

    public Apply(int id, String sname, String qq, long enterTime, String type, String school, long number, String repLink, String goal) {
        this.id = id;
        this.sname = sname;
        this.qq = qq;
        this.enterTime = enterTime;
        this.type = type;
        this.school = school;
        this.number = number;
        this.repLink = repLink;
        this.goal = goal;
    }

    public Apply(String sname, String qq, long enterTime, String type, String school, long number, String repLink, String goal) {
        this.sname = sname;
        this.qq = qq;
        this.enterTime = enterTime;
        this.type = type;
        this.school = school;
        this.number = number;
        this.repLink = repLink;
        this.goal = goal;
    }

    public long getId() {return id;}

    public void setId(long id) {this.id = id;}

    public String getSname() {return sname;}

    public void setSname(String sname) {this.sname = sname;}

    public String getQq() {return qq;}

    public void setQq(String qq) {this.qq = qq;}

    public long getEnterTime() {return enterTime;}

    public void setEnterTime(long enterTime) {this.enterTime = enterTime;}

    public String getType() {return type;}

    public void setType(String type) {this.type = type;}

    public String getSchool() {return school;}

    public void setSchool(String school) {this.school = school;}

    public long getNumber() {return number;}

    public void setNumber(long number) {this.number = number;}

    public String getRepLink() {return repLink;}

    public void setRepLink(String repLink) {this.repLink = repLink;}

    public String getGoal() {return goal;}

    public void setGoal(String goal) {this.goal = goal;}

}

bean 映射文件 apply.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="test">

    <!-- 在映射文件中配置很多 sql 语句 -->
    <!-- 将 sql 语句封装到 mappedStatement 对象中,所以将 id 称为 statement 的 id -->
    <!-- parameterType:指定输入参数的类型,这里指定 int 型 #{} 表示一个占位符号 -->
    <!-- #{id}:其中的 id 表示接收输入的参数,参数名称就是 id,如果输入 -->
    <!-- 参数是简单类型,#{} 中的参数名可以任意,可以 value 或其它名称 -->
    <!-- resultType:指定 sql 输出结果的所映射的 java 对象类型,select 指定 resultType 表示将单条记录映射成的 java 对象。-->
    <!-- 表名要对,但是不区分大小写,resultType 要写类名,同样不区分大小写 -->
    <select id="getApply" parameterType="int"  resultType="apply">
        SELECT * FROM applytable WHERE id = #{value}
    </select>

    <insert id="addApply" parameterType="bean.Apply">
        insert into applytable(id,sname, qq, entertime, `type`, school,`number`,replink,goal)
        values (
                null,
                #{sname},
                #{qq},
                #{enterTime},
                #{type},
                #{school},
                #{number},
                #{repLink},
                #{goal}
            )
    </insert>
    <update id="updateApply" parameterType="bean.Apply">
        update applytable set sname = #{sname}, qq = #{qq},
                entertime = #{enterTime}, `type` = #{type}, school = #{school},`number` = #{number}, replink = #{repLink}, goal = #{goal}
                where id = #{id}
    </update>
    <select id="getAllApply" resultType="bean.Apply">
        select * from applytable order by id desc
    </select>
    <select id="getTotalApply" resultType="int">
        select count(*) from applytable
    </select>
    <delete id="deleteApply" parameterType="int">
        delete from applytable where id = #{id}
    </delete>
</mapper>

数据库属性文件 config.properties

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/xiuzhenyuan?characterEncoding=UTF-8
jdbc.username = root
jdbc.password = admin

MyBatis 配置文件 mybatis-config.xml

<?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>

    <!-- 加载属性文件 -->
    <properties resource="config.properties">
        <!--properties 中还可以配置一些属性名和属性值 -->
        <!-- <property name="jdbc.driver" value=""/> -->
    </properties>

    <!-- 全局配置参数,需要时再设置 -->
    <!-- <settings> </settings> -->

    <typeAliases>
        <!-- 别名定义 -->
        <!-- 针对单个别名定义 type:类型的路径 alias:别名,类名不能写错
         别名可以随便起,但最好规范 -->
        <typeAlias type="bean.Apply" alias="apply" />
        <!-- 批量别名定义 指定包名,mybatis 自动扫描包中的 po 类,自动定义别名,别名就是类名(首字母大写或小写都可以)-->
        <package name="bean.Apply" />
    </typeAliases>

    <!-- 和 spring 整合后 environments 配置将废除 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用 jdbc 事务管理,事务控制由 mybatis -->
            <transactionManager type="JDBC" />
            <!-- 数据库连接池,由 mybatis 管理 -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>


    <!-- 加载映射文件 -->
    <mappers>
        <!-- 通过 resource 方法一次加载一个映射文件 -->
        <!-- 注意这里的路径和 xml 文件 -->
        <mapper resource="mappers/apply.xml" />

        <!-- 批量加载 mapper 指定 mapper 接口的包名,mybatis 自动扫描包下边所有 mapper 接口进行加载 -->
        <!-- 遵循一些规范:需要将 mapper 接口类名和 mapper.xml 映射文件名称保持一致,且在一个目录 -->
        <!-- 中上边规范的前提是:使用的是 mapper 代理方法
        <package name="...." />-->

    </mappers>

</configuration>

单元测试代码 ApplyTest.java

package com.jms;

import bean.Apply;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ApplyTest {public SqlSessionFactory getSqlSessionFactory() throws IOException {
        // mybatis 配置文件,这个地方的 root 地址为:resources,路径要对。String resource = "mybatis-config.xml";
        // 得到配置文件流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 创建会话工厂,传入 mybatis 的配置文件信息
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory;
    }

    // 根据 id 查询用户信息,得到一条记录结果
    @Test
    public void getApply() throws IOException {

        // 通过工厂得到 SqlSession
        SqlSession sqlSession = this.getSqlSessionFactory().openSession();

        // 通过 SqlSession 操作数据库
        // 第一个参数:映射文件中 statement 的 id,等于 =namespace+"."+statement 的 id
        // 第二个参数:指定和映射文件中所匹配的 parameterType 类型的参数
        // sqlSession.selectOne 结果 是与映射文件中所匹配的 resultType 类型的对象

        // selectOne 查询出一条记录(这种很麻烦的!!!往后看看)// 这里的参数 test.findUserById,test 为命名空间,要与 user.xml 中的对应起来,// 同理,findUserById 也要在 user.xml 中存在,不然都会报错
        Apply apply = sqlSession.selectOne("test.getApply", 2);
        // 释放资源
        sqlSession.close();}

    @Test
    public void addApply() throws IOException {SqlSession sqlSession = this.getSqlSessionFactory().openSession();
        sqlSession.insert("test.addApply", new Apply("Alice", "43523", 3452341, "Html", "SCHOOL", 4, "hgw3204", "DAY DAY UP"));
        sqlSession.commit();
        sqlSession.close();}

    @Test
    public void updateApply() throws IOException {SqlSession sqlSession = this.getSqlSessionFactory().openSession();
        sqlSession.update("test.updateApply", new Apply(2, "Alice", "43523", 3452341, "Html", "SCHOOL", 4, "hgw3204", "DAY DAY UP"));
        sqlSession.commit();
        sqlSession.close();}

    @Test
    public void getAll() throws IOException {SqlSession sqlSession = this.getSqlSessionFactory().openSession();
        final List<Apply> selectList = sqlSession.selectList("test.getAllApply");
        for (Apply apply :
                selectList) {System.out.println(apply);
        }
        sqlSession.close();}

    @Test
    public void getTotal() throws IOException {SqlSession sqlSession = this.getSqlSessionFactory().openSession();
        final Integer total = (Integer) sqlSession.selectOne("test.getTotalApply");
        System.out.println(total);
    }
    
    @Test
    public void delete() throws IOException {SqlSession sqlSession = this.getSqlSessionFactory().openSession();
        sqlSession.delete("test.deleteApply", 20);
        sqlSession.commit();
        sqlSession.close();}
}


单元测试结果

正文完
 0