Result Map还可以装入代表复杂类型对象集合(List)的属性,用以表示在数据库中相互关系为多对多或一对多的数据。拥有集合属性的类作为“一”的一方,而在集合中的对象作为“多”的一方。用来装入对象集合的mapped statement和上面例子一样。唯一的不同是,让SQL Map架构装入复杂类型集合(List)的业务对象的属性必须是java.util.List或java.util.Collection类型
映射文件:
- <!--complex type Collection property-->
- <resultMap id="get-product-result" class="product">
- <result property="id" column="prd_id"/>
- <result property="description" column="prd_description"/>
- <result property="price" column="prd_price"/>
- </resultMap>
- <resultMap id="get-categery-complex-list" class="category">
- <result property="id" column="cat_id"/>
- <result property="description" column="cat_description"/>
- <result property="productList" column="cat_id" select="getProductListByCatId"/>
- </resultMap>
- <select id="getCategory-complex-list" resultMap="get-categery-complex-list" parameterClass="int">
- <![CDATA[
- select * from t_category where cat_id = #value#
- ]]>
- </select>
- <select id="getProductListByCatId" resultMap="get-product-result" >
- <![CDATA[
- select * from t_product where prd_cat_id=#value#
- ]]>
- </select>
DAO层:
- public Category getProductUseComplexTypeList(int id) throws SQLException {
- init();
- Category category = (Category)sqlMapClient.queryForObject("getCategory-complex-list", id);
- return category;
- }
Test类:
- /**
- * 测试复杂类型集合的属性
- * @throws SQLException
- */
- public void getProductUseComplexTypeList() throws SQLException {
- Category category = productDao.getProductUseComplexTypeList(1);
- System.out.println(category);
- }
Category类:
- package com.ibatis.dataobject;
- import java.util.Iterator;
- import java.util.List;
- public class Category {
- @Override
- public String toString() {
- String temp = "Category---id:" + this.id + "\n" + "description:" + this.description;
- for (Iterator it=this.productList.iterator();it.hasNext();) {
- Product product = (Product)it.next();
- temp += "\n" + product.toString();
- }
- return temp;
- }
- private int id;
- private String description;
- private List productList;
- public List getProductList() {
- return productList;
- }
- public void setProductList(List productList) {
- this.productList = productList;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- }
结果:
Category---id:1
description:sports
Product----id:1
description:basketball
price:206.99
Product----id:2
description:football
price:106.99