resultType可以把查詢結果封裝到pojo類型中,但必須pojo類的屬性名和查詢到的資料庫表的欄位名一致。
如果sql查詢到的欄位與pojo的屬性名不一致,則需要使用resultMap將欄位名和屬性名對應起來,進行手動配置封裝,將結果映射到pojo中
resultMap可以實現將查詢結果映射為複雜類型的pojo,比如在查詢結果映射對象中包括pojo和list實現一對一查詢和一對多查詢。
先在Mapper文件中,配置基本的sql語句
<select id="queryOrderAll" resultMap="orderResultMap"> SELECT id, user_id, number, createtime, note FROM `order` </select>配置resultMap標籤,映射不同的欄位和屬性名
<resultMap type="order" id="orderResultMap"> <id property="id" column="id" />
<result property="userId" column="user_id" /> <result property="number" column="number" /> <result property="createtime" column="createtime" /> <result property="note" column="note" /> </resultMap>結果就可以封裝到pojo類型中
使用resultMap進行關聯查詢一對一查詢一對一數據模型:訂單用戶
一個訂單信息只會是一個人下的訂單,所以從查詢訂單信息出發關聯查詢用戶信息為一對一查詢。如果從用戶信息出發查詢用戶下的訂單信息則為一對多查詢,因為一個用戶可以下多個訂單。<resultMap type="order" id="orderUserResultMap"> <id property="id" column="id" /> <result property="userId" column="user_id" /> <result property="number" column="number" /> <result property="createtime" column="createtime" /> <result property="note" column="note" />
<association property="user" javaType="user"> <id property="id" column="user_id" /> <result property="username" column="username" /> <result property="address" column="address" /> </association>
</resultMap>
<select id="queryOrderUserResultMap" resultMap="orderUserResultMap"> SELECT o.id, o.user_id, o.number, o.createtime, o.note, u.username, u.address FROM `order` o LEFT JOIN `user` u ON o.user_id = u.id</select>測試
@Testpublic void testQueryOrderUserResultMap() { SqlSession sqlSession = this.sqlSessionFactory.openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<Order> list = userMapper.queryOrderUserResultMap(); for (Order o : list) { System.out.println(o); } sqlSession.close();}結果