MyBatis框架詳解—Dao 代理(下篇)

封裝 MyBatis?輸出結果
resultType
resultType: 執(zhí)行sql 得到 ResultSet 轉換的類型,使用類型的完全限定名或別名。 注意如果返回的是集合,那應該設置為集合包含的類型,而不是集合本身。resultType??和 resu?ltMap,不能同時使用。

A、 簡單類型
接口方法:
int countStudent();
mapper 文件:
<select id="countStudent"?
? ? ? ? resultType="int">?select count(*) from?
? ? ? ? student
</select>
測試方法:
@Test
public void testRetunInt(){
? ? ? ? int count = studentDao.countStudent();?
? ? ? ? System.out.println("學生總人數(shù):"+ count);
}
B、對象類型
接口方法:
Student selectById(int id);
mapper 文件:
<select id="selectById"?
? ? ? ? resultType="com.bjpowernode.domain.Student">?select?
? ? ? ? id,name,email,age from student where id=#{studentId}
</select>
?框架的處理: 使用構造方法創(chuàng)建對象。調(diào)用setXXX 給屬性賦值。
Student student = new Student();

注意:Dao 接口方法返回是集合類型,需要指定集合中的類型,不是集合本身。

C、Map
sql 的查詢結果作為 Map 的key 和value。推薦使用Map<Object,Object>。
注意:Map 作為接口返回值,sql 語句的查詢結果最多只能有一條記錄。大于一條記錄是錯誤。
接口方法:
Map<Object,Object> selectReturnMap(int id);
mapper 文件:
<select id="selectReturnMap" resultType="java.util.HashMap">?
? ? ? ?select name,email from student where id = #{studentId}
</select>
測試方法:
@Test
public void testReturnMap(){
? ? ? ? Map<Object,Object> retMap = studentDao.selectReturnMap(1002);? ?
? ? ? ??System.out.println("查詢結果是 Map:"+retMap);
}
resultMap
resultMap 可以自定義sql 的結果和 java 對象屬性的映射關系。更靈活的把列值賦值給指定屬性。
常用在列名和java 對象屬性名不一樣的情況。
使用方式:
1.先定義resultMap,指定列名和屬性的對應關系。
2.在<select>中把 resultType 替換為resultMap。
接口方法:
List<Student> selectUseResultMap(QueryParam param);
mapper 文件:

測試方法:

實體類屬性名和列名不同的處理方式
(1)?使用列別名和<resultType>
步驟:
1.?創(chuàng)建新的實體類 PrimaryStudent

2.?接口方法
List<PrimaryStudent> selectUseFieldAlias(QueryParam param);
3.?mapper?文件:

4.?測試方法

(2)?使用<resultMap>
步驟:
1.?接口方法
List<PrimaryStudent> selectUseDiffResultMap(QueryParam param);
2.?mapper?文件:

3. 測試方法

模糊 like
模糊查詢的實現(xiàn)有兩種方式, 一是java 代碼中給查詢數(shù)據(jù)加上“%” ;?二是在mapper?文件sql?語句的條件位置加上“%”
需求:查詢姓名有“力”的
例 1: java 代碼中提供要查詢的 “%力%”
接口方法:
List<Student> selectLikeFirst(String name);
mapper 文件:
<select id="selectLikeFirst"?
? ? ? ? resultType="com.bjpowernode.domain.Student">?select?
? ? ? ? id,name,email,age from student
? ? ? ? where name like #{studentName}
</select>
測試方法:
@Test
public void?
? ? ? ? testSelectLikeOne(){ String?
? ? ? ? name="%力%";
? ? ? ? List<Student> stuList = studentDao.selectLikeFirst(name);?
? ? ? ? stuList.forEach( stu -> System.out.println(stu));
}
例 2:mapper 文件中使用 like name "%" #{xxx} "%"
接口方法:
List<Student> selectLikeSecond(String name);
mapper 文件:
<select id="selectLikeSecond"
? ? ? ? resultType="com.bjpowernode.domain.Student">?select id,name,email,age?
? ? ? ?from student
? ? ? ?where name like "%" #{studentName} "%"
</select>
測試方法:
@Test
public void?
? ? ? ? testSelectLikeSecond(){ String?
? ? ? ? name="力";
? ? ? ? List<Student> stuList = studentDao.selectLikeSecond(name);?
? ? ? ? stuList.forEach( stu -> System.out.println(stu));
}
最后奉上視頻教程??,視頻觀看效果更佳?。∽哌^路過別忘素質(zhì)三連哦~~

