您的位置:首页 > 数据库

ibatis 复杂类型(用户自定义类型)

2008-06-23 12:49 274 查看
复杂类型用以表示在数据库中相互关系为一对一,一对多的数据。对于一对多的数据关
系,拥有复杂类型属性的类作为“多”的一方,而复杂属性本身则作为“一”的一方。

见DEMO:

<resultMap id="get-product-result" class="om.ibatis.example.Product">
    <result property="id" column="PRD_ID" />
    <result property="description" column="PRD_DECRIPTION"/>
    <result property="category" column="PRD_CAT_ID" slect="getCategory"/>
</resultMap>
<resultMap id="get-category-result" class"com.ibatis.example.Category">
    <result property="id" column="CAT_ID"/>
    <result property="dscription" column="CAT_DESCRIPTION"/>
</resultMap>

<statement id="getProduct" parameterClass="int" sultMap="get-product-result">
    select * from PRODUCT where PRD_ID = #value#
</statement>
<statement id="getCategory" parameterClass="int" rsultMap="get-category-result"
    select * from CATEGORY where CAT_ID = #value#
</statement>

// Product 对象拥有一个类型为 Category 的 category 属性,将 category 属性值和另
一个 mapped statement 联系起来,通过执行“getProduct”,“get-product-result” Result Map 使用 PRD_CAT_ID 字段的值去调用 “getCategory”,“get-category-result” Result Map将初始化一个 Category对象并赋值给它。然后整个 Category对象将赋值给 Product 的category属性。

避免 N+1 Select(1:1)

上面的方法存在一个问题,就是无论何时加载一个 Product,实际上都要执行两个 SQL
语句(分别加载 Product和 Category),在执行一个获得 10 个 Product的查询时,每得到一个 Product 都要分别执行一个加载 Category 的 SQL 语句。结果共执行了 11 次查询:一次用于得到一个 Product List,每得到一个 Product 对象都要执行另外一次查询,以获得相应的 Category 对象(N+1,这个例子是10+1=11)。

解决方法是,使用一个联合查询和嵌套的属性映射来代替两个查询 statement。上面例
子的解决方案是:

<resultMap id="get-product-result" class="com.ibatis.example.Product">
    <result property="id" column="PRD_ID"/>
    <result property="description" column="PRD_DECRIPTION"/>
    <result property="category.id" olumn="CAT_ID" />
    <result property="category.description" column="CAT_DESCRIPTION" />

</resultMap>

<statement id="getProduct" parameterClass="int" resultMap="get-product-result">
select *
from PRODUCT, CATEGORY
where PRD_CAT_ID=CAT_ID
and PRD_ID = #value#
</statement>

复杂类型集合的属性
Result Map还可以装入代表复杂类型对象集合(List)的属性,用以表示在数据库中相互关系为多对多或一对多的数据
(假设 Category类有一个叫 productList 的属性,类型是 java.util.List)

<resultMap id="get-category-result" class"com.ibatis.example.Category">
<result property="id" column="CAT_ID"/>
<result property="description" column="CAT_DESCRIPTION"/>
<result property="produtList" 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_DECRIPTION"/>
</resultMap>
<statement id="getCategory" parameterClass="int" resultMap="get-category-result"
select * from CATEGORY where CAT_ID = #value#
</statement>
<statement id="getProductsByCatId" prameterClass="int" resultMap="get-product-result">
select * from PRODUCT where PRD_CAT_ID = #value#
</statement>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ibatis class 数据库 list sql