ibatis 实现一对一和一对多(2)

ibatis 实现一对一和一对多(2)

 

<sqlMap namespace="test">
<typeAlias alias="Key" type="zzcv.dao.domain.Key"/>
<typeAlias alias="Lock" type="zzcv.dao.domain.Lock"/>

<resultMap id="KeyResult" class="Key">
<result property="id" column="id"/>
<result property="keyName" column="keyName"/>
<result property="lock" column="lockId" select="getLockById"/>
</resultMap>
<!-- 通过key表中保存的lock的id实现的一对一关联,ibatis会使用getLockById(lockId)的结果填充lock属性 -->

<resultMap id="LockResult" class="Lock">
<result property="id" column="id"/>
<result property="lockName" column="lockName"/>
<result property="keys" column="id" select="getKeysByLockId"/>
</resultMap>
<!-- 通过lock的id实现的一对多关联,ibatis会使用getKeysByLockId(id)得到的List填充keys属性 -->

<!-- 多对多可以通过嵌套实现,这里就不列出了 -->

<select id="selectAllkeys" resultMap="KeyResult">
<![CDATA[
select id,lockId,keyName from key
]]>
</select>

<select id="getLockById" parameterClass="int" resultClass="Lock">
<![CDATA[
select id,lockName from lock where id = #value#
]]>
</select>

<select id="selectAllLocks" resultMap="LockResult">
<![CDATA[
select id,lockName from lock
]]>
</select>

<select id="getKeyByLockId" resultClass="KeyResult">
<![CDATA[
select id,lockId,keyName from key where id= #value#
]]>
</select>
</sqlMap>
现在可以代码中使用了

...
..
try{
Reader reader = Resources.getResourceAsReader("mxd/dao/data/SqlMapConfig.xml");
sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close(); }
catch(IOException e){
throw new RuntimeException("Something bad happened while building the SqlMapClient instance." + e, e);}

List locks=sqlMapper.queryForList("selectAllLocks");
//取一个Lock对象。
Lock lock=(Lock)locks.get(0);
//从Lock对象取List<Key>。
List keys=lock.getKeys();
//示例结束,取到结果了,剩余的一个关联是取对象Lock,其余操作差不多,就不写出了。
...
.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值