MyBatis筆記03——XXXMapper.xml文件解析

SQL映射文件的配置解析

  當我們寫好mapper(dao)層接口時,然後在對應的XXXMapper.xml文件中寫業務邏輯對應的SQL映射語句,通過這個文件中可以實現CRU操作,那麼下面說明如何編寫這個.xml文件。

一、.xml文件的內容

1、頭文件內容(固定)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "//mybatis.org/dtd/mybatis-3-mapper.dtd">

2、簡單的CRUD操作

<mapper namespace="com.dao.StuMapper">
    <select id="queryAll" resultType="stu">
     <!--查詢-->
        select * from stu;
    </select>
    <select id="queryByKey" parameterType="int" resultType="com.pojo.Stu">
     <!--in根據主鍵查詢-->
        select * from stu where sno=#{sno};
    </select>
    <insert id="insert" parameterType="com.pojo.Stu">
        <!--增加-->
        insert into stu value(#{sno},#{sname},#{sage},#{saddress},#{spwd});
    </insert>
    <update id="upd" parameterType="com.pojo.Stu">
        <!--更新-->
        update stu set sname=#{sname},sage=#{sage},saddress=#{saddress},spwd=#{spwd}
        where sno=#{sno};
    </update>
    <delete id="del" parameterType="int">
        <!--刪除-->
        delete  from stu where sno=#{sno};
    </delete>
</mapper>

顯而易見:1、配置SQL映射語句,首先使用<mapper>標籤,其中namespace屬性代表命名,它的屬性值是.xml文件對應的XXXMapper(dao)

                      接口的完整包名接口名

               2、<select>標籤:實現查詢功能                            <update>標籤:  實現更新功能

                    <insert>標籤:   實現插入功能                             <delete>標籤;   實現刪除功能

二、select、insert、update、delete標籤的配置

1、這四個標籤是完成CRUD操作的

2、這四個標籤主要都有id屬性,paramType屬性,resultType屬性(這三個屬性常用)

id屬性:屬性值是對應的XXXMapper接口中的方法名,屬性值一定要與方法名一模一樣!!!是必須寫的

paramType屬性:屬性值是對應的XXXMapper接口中方法對應的參數類型,當接口中的方法的參數是Map集合,那麼它的屬性值是map(小寫的)

resultType屬性: 屬性值是對應的XXXMapper接口中方法的返回類型

注意:在MyBatis中開啟了事務,但是自動提交事務默認為false,所以我們需要手動提交事務,這樣對應的操作才會對數據庫生效!!!所以像增加、更新、刪除操作都需要手動提交事務

手動提交事務:sqlSession.commit();//sqlSession是一個引用,是連接數據庫的對象

開啟提交事務默認為true:sqlSessionFactory.openSession(true);//sqlSessionFactory是一個引用,是SqlSessionFactory的對象,