Mybatis(二)— 模糊查詢兩種方式和 resultMap結果類型

模糊查詢

  • 第一種方法
<!-- 根據名稱模糊查詢 -->
 <select id="findByName" resultType="com.itheima.domain.User" parameterType="String">
	select * from user where username like #{username}
</select>
  • 第二種方法
<!-- 根據名稱模糊查詢 -->
 <select id="findByName" parameterType="string" resultType="com.itheima.domain.User">
	select * from user where username like '%${value}%'
</select>

所以 ,兩方法比較 #{}與${}的區別

#{}表示一個佔位符號
通過#{}可以實現 preparedStatement 向佔位符中設置值,自動進行 java 類型和 jdbc 類型轉換,
#{}可以有效防止 sql 注入。 #{}可以接收簡單類型值或 pojo 屬性值。 
如果 parameterType 傳輸單個簡單類型值,#{}括號中可以是 value 或其它名稱。
${}表示拼接 sql 串
通過${}可以將 parameterType 傳入的內容拼接在 sql 中且不進行 jdbc 類型轉換, ${}可以接收簡
單類型值或 pojo 屬性值,如果 parameterType 傳輸單個簡單類型值,${}括號中只能是 value。

resultMap 的使用

  • 條件:此時的實體類屬性和數據庫表的列名已經不一致
  • 第一種方法:使用別名查詢
<!-- 配置查詢所有操作 -->
<select id="findAll" resultType="com.itheima.domain.User">
	select id as userId,username as userName,birthday as userBirthday,
sex as userSex,address as userAddress from user
</select>
  • 第二種方法: resultMap的使用
  • resultMap 結果類型:
  1. resultMap 標籤可以建立查詢的列名和實體類的屬性名稱不一致時建立對應關係。從而實現封裝。
  2. 在 select 標籤中使用 resultMap 屬性指定引用即可。同時 resultMap 可以實現將查詢結果映射爲複雜類型的 pojo,比如在查詢結果映射對象中包括 pojo 和 list 實現一對一查詢和一對多查詢。
  • 配置如下:
<!-- 建立 User 實體和數據庫表的對應關係
	type 屬性:指定實體類的全限定類名
	id 屬性:給定一個唯一標識,是給查詢 select 標籤引用用的。
--> 
<resultMap type="com.itheima.domain.User" id="userMap">
	<id column="id" property="userId"/>
	<result column="username" property="userName"/>
	<result column="sex" property="userSex"/>
	<result column="address" property="userAddress"/>
	<result column="birthday" property="userBirthday"/>
</resultMap>
	id 標籤:用於指定主鍵字段
	result 標籤:用於指定非主鍵字段
	column 屬性:用於指定數據庫列名
	property 屬性:用於指定實體類屬性名稱

  • 映射配置
<!-- 配置查詢所有操作 --> 
<select id="findAll" resultMap="userMap">
	select * from user
</select>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章