Mybatis連結3表查詢數據resultMap結果映射
一、前言
二、從sql查詢結果到模型實體
在深入ResultMap標籤前,我們需要了解從SQL查詢結果集到JavaBean或POJO實體的過程。
1. 通過JDBC查詢得到ResultSet對象
2. 遍歷ResultSet對象並將每行數據暫存到HashMap實例中,以結果集的字段名或字段別名爲鍵,以字段值爲值
3. 根據ResultMap標籤的type屬性通過反射實例化領域模型
4. 根據ResultMap標籤的type屬性和id、result等標籤信息將HashMap中的鍵值對,填充到領域模型實例中並返回
三、ResultMap標籤
id屬性:標識resultMap,通過它去識別.
type屬性:返回值類型,類的全定向名.
autoMapping屬性:值爲true(默認)|false,是否自動映射。自動映射功能就是自動查找與字段名小寫同名的屬性名,並調用setter方法。而設置爲false後,則需要在`resultMap`內明確註明映射關係纔會調用對應的setter方法。
四、ResultMap中子標籤
在講標籤時先講述下數據庫中表數據的對應關係,如一對一,一對多,多對多等關係,具體來說,如有一個俱樂部表,一個全員表,一個俱樂部裏有許多球員,而許多球員對應一個俱樂部,則俱樂部與球員之間的關係就是一對多與多對一的關係。
<collection>子標籤:對應表格關係中的多
<association>子標籤:對應表格關係中的一
五、聯結三表示例
<!-- 結果映射 -->
<resultMap type="com.sxt.entity.Club" id="clubBean" autoMapping="true">
<!--column指向數據庫列名 property指向pojo對象中字段名-->
<result column="cid" property="cid"/>
<result column="cname" property="cname"/>
<result column="city" property="city"/>
<!-- property指的是在bean中字段名 ofType類的全定向名 -->
<collection property="players" ofType="com.sxt.entity.Player">
<result column="pid" property="pid"/>
<result column="pname" property="pname"/>
<result column="position" property="position"/>
<result column="cid" property="cid"/>
<association property="abilities" javaType="com.sxt.entity.Abilities">
<result column="aid" property="aid"/>
<result column="pid" property="pid"/>
<result column="shoot" property="shoot"/>
</association>
</collection>
</resultMap>
clubMapper.xml中sql語句<select id="joinTwo" resultMap="clubBean">
select c.*,p.*,a.*
from clubs c
join player p
on c.cid = p.cid
join abilities a
on a.pid = p.pid;
</select>
playerMapper.xml中的結果映射:<!-- 結果映射 -->
<resultMap type="com.sxt.entity.Player" id="playerBean">
<!--column指向數據庫列名 property指向pojo對象中字段名 -->
<result column="pid" property="pid" />
<result column="pname" property="pname" />
<result column="position" property="position" />
<result column="cid" property="cid" />
<association property="club" javaType="com.sxt.entity.Club">
<result column="cid" property="cid" />
<result column="cname" property="cname" />
<result column="city" property="city" />
</association>
<association property="abilities" javaType="com.sxt.entity.Abilities">
<result column="aid" property="aid"/>
<result column="pid" property="pid"/>
<result column="shoot" property="shoot"/>
</association>
</resultMap>
abilitiesMapper.xml結果映射<!-- 結果映射 -->
<resultMap type="com.sxt.entity.Abilities" id="abilitiesBean">
<!--column指向數據庫列名 property指向pojo對象中字段名 -->
<result column="aid" property="aid"/>
<result column="pid" property="pid"/>
<result column="shoot" property="shoot"/>
<association property="player" javaType="com.sxt.entity.Player">
<result column="pid" property="pid"/>
<result column="pname" property="pname"/>
<result column="position" property="position"/>
<result column="cid" property="cid"/>
</association>