MyBatis映射文件的基本功能

#{}與${}區別

  1. #{}使用的是preparedStatement方式預處理,就是使用了佔位符來填充數據防止SQL注入.

  2. ${}使用的是statement方式進行sql語句的拼接操作,有SQL注入風險。

映射文件配置:

    <delete id="delete" parameterType="int">
		delete from t_user where no = #{no} 
	</delete>
	
	<delete id="deleteById" parameterType="int">
		delete from t_user where no = ${no} 
	</delete>

測試代碼:

@Test
	public void test2() {
		int add = mapper.delete(1010);
		System.out.println("刪除了"+add+"條信息");
	}
	
	@Test
	public void test3() {
		int add = mapper.deleteById(1111);
		System.out.println("刪除了"+add+"條信息");
	}

測試結果:
在這裏插入圖片描述
3. ${}使用時必須在接口的參數上面使用註解@Parma(“參數名”)來定義參數,否則會報錯。

resultType與resultMap區別

  1. resultType用來設置SQL事務操作返回的數據是什麼類型的。(一般用在單表處理中)

  2. resultMap基本功能在resultType的基礎上增加了返回類型數據名稱的別名設置,就是針對,引用類型的成員名稱與數據庫表單的數據名稱不一致的情況。(一般使用在多表聯級查處理中)

映射文件設置

<resultMap type="user" id="baseMap">
		<!-- 通常使用在多級聯表查詢中,由於表中的屬性
			  名與後端對應類的成員名稱對不上,所以可以
			  在此處定義成員變量的別名使查詢結果一一對
			  應,方便數據接收 -->
  		<!-- 表結構中的column和對象中成員變量對應關係 -->
  		<id column="no" property="no"/>
  		<result column="name" property="xxxname"/>
  		<result column="age" property="age"/>
  	</resultMap>
  	
  	<!-- 
  		resultType一般用在單表處理中 
  		resultMap 一般使用在多表中
  	-->
  	<select id="query" resultMap="baseMap">
		select * from t_user 
	</select>
	<select id="queryById" resultType="user" parameterType="int">
		select * 
		from t_user 
		where no=#{id}
	</select>

查詢測試,已經提前將User類中的name成員名改成了xxxname,與數據庫中的name不一致:

@Test
	public void test() {
		List<User> list = mapper.query();
		for (User user : list) {
			System.err.println("使用了resultMap"+user);
		}
		User byId = mapper.queryById(1111);
		System.err.println("使用了resultType"+byId);
	}

查詢結果,可以看到沒有設置成員別名的成員值是NULL:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章