Result Map还可以装入代表复杂类型对象集合(List)的属性,用以表示在数据库中相互关系为多对多或一对多的数据。拥有集合属性的类作为“一”的一方,而在集合中的对象作为“多”的一方。用来装入对象集合的mapped statement和上面例子一样。唯一的不同是,让SQL Map架构装入复杂类型集合(List)的业务对象的属性必须是java.util.List或java.util.Collection类型
映射文件:
- <!--complextypeCollectionproperty-->
- <resultMapid="get-product-result"class="product">
- <resultproperty="id"column="prd_id"/>
- <resultproperty="description"column="prd_description"/>
- <resultproperty="price"column="prd_price"/>
- </resultMap>
- <resultMapid="get-categery-complex-list"class="category">
- <resultproperty="id"column="cat_id"/>
- <resultproperty="description"column="cat_description"/>
- <resultproperty="productList"column="cat_id"select="getProductListByCatId"/>
- </resultMap>
- <selectid="getCategory-complex-list"resultMap="get-categery-complex-list"parameterClass="int">
- <![CDATA[
- select*fromt_categorywherecat_id=#value#
- ]]>
- </select>
- <selectid="getProductListByCatId"resultMap="get-product-result">
- <![CDATA[
- select*fromt_productwhereprd_cat_id=#value#
- ]]>
- </select>
DAO层:
- publicCategorygetProductUseComplexTypeList(intid)throwsSQLException{
- init();
- Categorycategory=(Category)sqlMapClient.queryForObject("getCategory-complex-list",id);
- returncategory;
- }
Test类:
- /**
- *测试复杂类型集合的属性
- *@throwsSQLException
- */
- publicvoidgetProductUseComplexTypeList()throwsSQLException{
- Categorycategory=productDao.getProductUseComplexTypeList(1);
- System.out.println(category);
- }
Category类:
- packagecom.ibatis.dataobject;
- importjava.util.Iterator;
- importjava.util.List;
- publicclassCategory{
- @Override
- publicStringtoString(){
- Stringtemp="Category---id:"+this.id+"\n"+"description:"+this.description;
- for(Iteratorit=this.productList.iterator();it.hasNext();){
- Productproduct=(Product)it.next();
- temp+="\n"+product.toString();
- }
- returntemp;
- }
- privateintid;
- privateStringdescription;
- privateListproductList;
- publicListgetProductList(){
- returnproductList;
- }
- publicvoidsetProductList(ListproductList){
- this.productList=productList;
- }
- publicintgetId(){
- returnid;
- }
- publicvoidsetId(intid){
- this.id=id;
- }
- publicStringgetDescription(){
- returndescription;
- }
- publicvoidsetDescription(Stringdescription){
- this.description=description;
- }
- }
结果:
Category---id:1
description:sports
Product----id:1
description:basketball
price:206.99
Product----id:2
description:football
price:106.99