mybatis的一對多映射

    延續mybatis的一對一問題,還是上面一對一舉得那個例子(http://fengcl.blog.51cto.com/9961331/1875657),

如果一個用戶有多個作品怎麼辦?這就涉及到了一對多的問題。同樣的,mybatis一對多依然可以分爲兩種方式來解決。

一、使用內嵌的ResultMap實現一對多映射

1)實體

public class User implements Serializable{
    private static final long serialVersionUID = 112596782083832677L;
    private Integer id;			//編號
    private String email; 		//郵箱
    private String realName; 	//真實姓名
    private String telephone;   //電話號碼
    
    private List<WorksInfo> worksInfos; //作品
    //get,set方法
    ...
}

public class WorksInfo implements Serializable{
    private Integer id;
    private  Integer userId;
    private Date uploadDate; //上傳時間
    private Date updateDate; //更新時間
    //get,set方法
    ...
}

2)dao接口省略...

3)mapper映射文件

<resultMap type="com.tarena.djs.entity.WorksInfo" id="worksInfoResultMap">
    <id column="id" property="id" />
    <result column="uploadDate" property="uploadDate" />
    <result column="updateDate" property="updateDate" />
</resultMap>
<resultMap type="com.tarena.djs.entity.User" id="UserResult">
    <id column="id" property="id" /> 
    <result column="email" property="email" />
    <result column="telephone" property="telephone" />
    <result  column="realName"  property="realName"/>
    <collection property="worksInfos" resultMap="worksInfoResultMap" />
</resultMap>
<select id="findTutorById" parameterType="int" resultMap="UserResult">
    select u.*,w.* 
    from user u 
    left join worksInfo w 
    on u.id = w.userId 
    where u.id = #{id}    
</select>

4)測試省略

二、嵌套查詢方式實現一對多

1)實體類如上

2)dao層接口省略

3)mapper文件映射

<resultMap type="com.tarena.djs.entity.WorksInfo" id="worksInfoResultMap">
    <id column="id" property="id" />
    <result column="uploadDate" property="uploadDate" />
    <result column="updateDate" property="updateDate" />
</resultMap>
<select id="findWorksInfoByUserId" parameterType="int" resultMap="worksInfoResultMap">
    select * from worksInfo where userId = #{userId}
</select>
<resultMap type="com.tarena.djs.entity.User" id="UserResult">
    <id column="id" property="id" /> 
    <result column="email" property="email" />
    <result column="telephone" property="telephone" />
    <result  column="realName"  property="realName"/>
    <collection property="worksInfos" columns="id" select="findWorksInfoByUserId" />
</resultMap>
<select id="findUserByUserId" parameterType="int" resultMap="UserResult">
    select * from user where id = #{id}
</select>

4)測試方法忽略

注意:collention元素裏的column屬性,即主表中要傳遞給副表做查詢的條件,例如本例中:

<collection property="worksInfos" columns="id" select="findWorksInfoByUserId" />

及時將user表中的id字段傳遞給findWorksInfoByUserId方法做參數使用的,對應worksInfo表中的userId字段。除此之外,嵌套select語句會導致N+1的問題。首先,主查詢將會執行(1 次) ,對於主

查詢返回的每一行,另外一個查詢將會被執行(主查詢 N 行,則此查詢 N 次) 。對於

大型數據庫而言,這會導致很差的性能問題。 




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章