Mybatis之collection標簽中javaType和ofType屬性的區(qū)別說明
collection標簽中的javaType和ofType屬性的區(qū)別
在使用mybatis時,有時候需要在數(shù)據(jù)庫中進行關(guān)聯(lián)查詢(left/right join)來根據(jù)某個字段獲取到另一個表的的一個List集合。
在配置resultMap時,需要用到collection標簽對這個LIst屬性進行映射:
比如在部門表中有一個列表List存放這個表中的所有員工,javaBean如下:
public class Department { private Integer id; private String departmentName; private List<Employee> emps; }
員工表如下:
public class Employee { private Integer id; private String lastName; private String email; private String gender; }
用mybatis對這兩個表進行關(guān)聯(lián)查詢查詢
<select id="getDeptByIdPlus" resultMap="MyDept"> SELECT d.id did, d.dept_name dept_name, e.id eid, e.last_name last_name, e.email email,e.gender gender FROM department d LEFT JOIN employee e ON d.id = e.d_id WHERE d.id = 1 </select>
由于是通過關(guān)聯(lián)查詢得到的這個List
所以此時需要用到resultMap標簽對返回值的類型進行自定義:
<resultMap type="bean.Department" id="MyDept"> <id column="did" property="id"/> <result column="dept_name" property="departmentName"/> <!-- collection定義關(guān)聯(lián)的集合類型的屬性的封裝規(guī)則: property="emps":指定這是哪個集合屬性,這里為那個集合屬性emps ofType:指定集合內(nèi)封裝的JavaBean類型(集合內(nèi)裝的什么),這里即為Employee類 --> <collection property="emps" ofType="bean.Employee"> <!-- 定義集合中元素的封裝規(guī)則 --> <id column="eid" property="id"/> <result column="last_name" property="lastName"/> <result column="email" property="email"/> <result column="gender" property="gender"/> </collection> </resultMap>
在這個resultMap 標簽中,用collection這個子標簽對這個List進行映射。通過Alt+/可以發(fā)現(xiàn),collection標簽中包含兩個關(guān)于javaBean的Type屬性分別是ofType和javaType。
其中ofType指定的這個List所存放的javaBean的類型,比如這里就是Employee類型。
而javaType指定的當前這個配置的標簽所對應(yīng)的屬性,比如我們這里的collection配置的是一個List,就可以配置成javaType=“java.util.ArrayList”(此處沒寫)。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java數(shù)據(jù)結(jié)構(gòu)及算法實例:三角數(shù)字
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)及算法實例:三角數(shù)字,本文直接給出實現(xiàn)代碼,代碼中包含詳細注釋,需要的朋友可以參考下2015-06-06詳談鎖和監(jiān)視器之間的區(qū)別_Java并發(fā)
下面小編就為大家?guī)硪黄斦勬i和監(jiān)視器之間的區(qū)別_Java并發(fā)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06