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

相關文章
相關標籤/搜索