`

ibatis resultMap 嵌套list应用

阅读更多

复杂类型集合的属性:
Result Map还可以装入代表复杂类型对象集合(List)的属性,用以表示在数据库中相互关系为多对多或一对多的数据。拥有集合属性的类作为“一”的一方,而在集合中的对象作为“多”的一方。用来装入对象集合的mapped statement和上面例子一样。唯一的不同是,让SQL Map架构装入复杂类型集合(List)的业务对象的属性必须是java.util.List或java.util.Collection类型。    
<resultMap id=”get-category-result” class=”com.ibatis.example.Category”>
      <result property=”id” column=”CAT_ID”/>
      <result property=”description” column=”CAT_DESCRIPTION”/>
      <result property=”productList” column=”CAT_ID” select=” getProductsByCatId”/>
</resultMap>
<resultMap id=”get-product-result” class=”com.ibatis.example.Product”>
      <result property=”id” column=”PRD_ID”/>
      <result property=”description” column=”PRD_DESCRIPTION”/>
</resultMap>
<statement id=”getCategory” parameterClass=”int” resultMap=”get-category-result”>
      select * from CATEGORY where CAT_ID = #value#
</statement>
<statement id=”getProductsByCatId” parameterClass=”int” resultMap=”get-product-result”>
      select * from PRODUCT where PRD_CAT_ID = #value#
</statement>
上面一次执行的顺序是3->1->4->2。


组合键值或多个复杂参数属性:
在有多个属性之互相关联的时候就用下面的这种格式:
<resultMap id=”get-order-result” class=”com.ibatis.example.Order”>
      <result property=”id” column=”ORD_ID”/>
      <result property=”customerId” column=”ORD_CST_ID”/>
      …
      <result property=”payments” column=”{itemId=ORD_ID, custId=ORD_CST_ID}” select=” getOrderPayments”/>
</resultMap>
<statement id=”getOrderPayments” resultMap=”get-payment-result”>
      select * from PAYMENT where PAY_ORD_ID = #itemId# and PAY_CST_ID = #custId#
</statement>

parameterClass属性是可选的,但强烈建议使用。它的目的是限制输入参数的类型为指定的Java类,并优化框架的性能。如果您使用parameterMap,则没有必要使用parameterClass属性。


parameterMap属性的值等于一个预先定义的<parameterMap>元素的名称。


resultClass属性可以让您指定一个Java类,根据ResultSetMetaData将其自动映射到JDBC的ResultSet。只要是Java Bean的属性名称和ResultSet的列名匹配,属性自动赋值给列值。这使得查询mapped statement变得很短。如:
<statement id="getPerson" parameterClass=”int” resultClass="examples.domain.Person">
SELECT PER_ID as id,
PER_FIRST_NAME as firstName,
PER_LAST_NAME as lastName,
PER_BIRTH_DATE as birthDate,
PER_WEIGHT_KG as weightInKilograms,
PER_HEIGHT_M as heightInMeters
FROM PERSON
WHERE PER_ID = #value#
</statement>


resultMap可以控制数据如何从结果集中取出,以及哪一个属性匹配哪一个字段。不象使用resultClass的自动映射方法,resultMap属性可以允许指定字段的数据类型,NULL的替代值复杂类型映射(包括其他Java Bean,集合类型和基本类型包装类)。如:
<resultMap id=”get-product-result” class=”com.ibatis.example.Product”>
<result property=”id” column=”PRD_ID”/>
<result property=”description” column=”PRD_DESCRIPTION”/>
</resultMap>
<statement id=”getProduct” resultMap=”get-product-result”>
select * from PRODUCT
</statement>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics