SSM框架-MyBatis進階篇(一)
阿新 • • 發佈:2019-01-03
一、MaBatis
本篇目的介紹一下在開發過程中使用mabtis,如何自己去操作資料庫以及如何將表之間的關係建立聯絡.當在Mapper的介面檔案中寫入多個方法對資料庫進行操作時,需要在對應的xml
檔案中,寫入多條select
,insert
,delete
等語句,此時可以在xml檔案中用結果對映的方式進行統一匹配處理,程式碼如下:
<!--namespace:一般寫對應的介面路徑-->
<mapper namespace="com.lanou.mapper.StudentMapper">
<!--MyBatis的結果對映:
如果當實體類的屬性名和資料庫表的列名不一致的情況下,
需要使用結果對映來確保資料的一致性
要求:需要將所有的對映寫在sql語句之上
-->
<resultMap id="BaseMap" type="com.lanou.bean.Student">
<!--
column:資料庫表的列名.property:實體類的屬性名
id:只有這個是特殊的
其他的都用result即可
-->
<id column="id" property="id"/>
<result column="name" property="name"/>
</resultMap >
二、寫上結果對映後,在寫select等執行語句時,可以用resultMap=”ID”的形式進行對映,示例如下:
<select id="allListStudent" resultMap="BaseMap">
SELECT * FROM student
</select>
三、資料庫查詢語句中,Mybats提供一種方法,可以將查詢條件歸集到一個標籤中,將其ID設定好,這樣用到對應條件的引數時,可以根據ID來進行操作,方便使用,示例如下:
<!--儲存一段sql片段,以供反覆使用-->
<sql id="WaHaHa">
id,name
</sql>
<select id="allListStudent" resultMap="BaseMap">
SELECT
<include refid="WaHaHa"/>
FROM student
</select>
四、當對資料庫進行增刪改查等多項操作時,有時需要考慮根據某項引數來進行操作,或者直接操作實體類物件,程式碼如下:
public interface StudentMapper {
//查詢所有的學生
List<Student> allListStudent();
//如果引數有多個,需要使用@Param註解規定引數的別名
void insertStudent(@Param("sname") String name);
//直接插入student
void insertStu(Student student);
//刪除
void deleteStudent(@Param("sid") Integer id);
//更新資料
void updateStudent(Student student);
}
五、根據以上程式碼可以知道,用註解@Param的方式對引數進行規定別名,在xml檔案中要與設定的別名對應上,其中的Type,需要用到的是parameterType,對映到具體的實體類但是該parameterType可寫可不寫,xml程式碼如下:
<insert id="insertStudent">
INSERT INTO student VALUES (NULL,#{sname});
</insert>
<insert id="insertStu" parameterType="com.lanou.bean.Student">
INSERT INTO student VALUES (NULL ,#{name})
</insert>
<delete id="deleteStudent">
DELETE FROM student WHERE id=#{sid};
</delete>
<update id="updateStudent">
UPDATE student SET name=#{name} WHERE id = #{id};
</update>