輸出映射:
第一種:
resultType指定相應的返回結果類型進行輸出映射
只有查詢出來的列名與pojo中的屬性名一致,纔會映射成功創建pojo
若全部都不一致,則沒有創建pojo,查詢出來的結果類型都是空
若有一個一致,就會創建pojo,但是其他不一致的屬性也會返回空
首先,來個需求:
我們查詢綜合用戶信息時可能需要它的總數來進行分頁:
解決:
<!-- 綜合查詢用戶信息總數 -->
<select id="findUserCount" parameterType="com.ddd.mybatis.pojo.UserQueryVo" resultType="int">
SELECT COUNT(*) FROM USER WHERE sex='男' AND username LIKE '%張偉%'
</select>
接口方法:
//綜合查詢用戶信息總數
public int findUserCount(UserQueryVo userQueryVo);
測試:
@Test
public void testFindUserCount() {
//由於之前是在UserDaoImpl中每次獲取sqlSession,所以這裏需要我們手動寫
SqlSession sqlSession=sqlSessionFactory.openSession();
//mybatis自動生成mapper代理對象,代理對象內部調用selectOne或者selectList
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
//調用userMapper的方法,但這裏如果不小心用一個單個user來接收,那會報錯
UserQueryVo userQueryVo=new UserQueryVo();
UserCustom userCustom=new UserCustom();
userCustom.setSex("男");
userCustom.setUsername("張偉");
int count=userMapper.findUserCount(userQueryVo);
System.out.println(count);
}
結果:
3
ps:
1.如果查詢出來的結果只有一行or一列,可以使用簡單類型進行輸出映射
2.不管輸出是單個對象還是多個對象,resultType都一樣指定的是單條記錄的返回結果,而不同的是mapper的接口方法的返回值類型接收不同,動態代理對象會根據這個返回值來選擇selectOne還是selectList
第二種:
resultMap:完成高級輸出結果映射
當查詢出來的列名和pojo的屬性名不一致的時候,就需要定義一個resultMap對列名和pojo屬性名之間做一個映射關係
1.定義resultMap
我們在數據庫中這樣查詢:
SELECT id id_,username username_ FROM USER WHERE id=13
很明顯,這些id_和username_和User中的屬性名都不一致
那麼我們需要定義resultMap來完成這個sql語句中的屬性的別名和pojo中的不一致問題·
<!-- 定義resultMap
將SELECT id id_,username username_ FROM USER WHERE id=13
中的屬性名和user中的屬性名做一個映射
type:是resultMap最終映射的Java對象類型,可以使用別名
id:是對resultMap的唯一標識
如果被其他的mapper文件引用,需要在前面加namespace
-->
<resultMap type="user" id="userResultMap">
<!-- id表示查詢結果的唯一標識,column:查詢出來的列名 property:type屬性中pojo的屬性名 相當於一箇中間人完成兩個屬性名的適配·-->
<id column="id_" property="id"/>
<result column="username_" property="username"/>
</resultMap>
定義之後將其作爲返回輸出映射:
<!-- 通過resultMap作爲輸出映射 -->
<select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">
SELECT id id_,username username_ FROM USER WHERE id=#{id}
</select>
接口方法:
//返回值爲ResultMap的查詢
public User findUserByIdResultMap(int id);
測試:
@Test
public void testFindUserByIdResultMap() {
//由於之前是在UserDaoImpl中每次獲取sqlSession,所以這裏需要我們手動寫
SqlSession sqlSession=sqlSessionFactory.openSession();
//mybatis自動生成mapper代理對象,代理對象內部調用selectOne或者selectList
UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
//調用userMapper的方法
User u=userMapper.findUserByIdResultMap(13);
System.out.println(u);
}
小結:
查詢出來的列名與pojo中的屬性名不一致,使用resultMap來作爲中間的橋樑做一個映射