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

总体项目结构

2.png

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();
    }
}

单元测试结果

3.png

相关文章
相关标签/搜索