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

复杂类型用以表示在数据库中相互关系为一对一一对多 的数据。对于一对多的数据关 系,拥有复杂类型属性的类作为“多”的一方,而复杂属性本身则作为“一”的一方。 见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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值