IBatis.Net学习笔记六--再谈查询

在ibatis.net学习笔记五--常用的查询方式 中我提到了一些ibatis.net中的查询,特别是配置文件的写法。

后来通过大家的讨论,特别是anders cui 的提醒,又发现了其他的多表查询的方式。
在上一篇文章中我提到了三种方式,都是各有利弊:
第一种方式当数据关联很多的情况下,实体类会很复杂;
第二种方式比较灵活,但是不太符合oo的思想(不过,可以适当使用);
第三种方式最主要的问题就是性能不太理想,配置比较麻烦。

下面是第四种多表查询的方式,相对第二种多了一点配置,但是其他方面都很好
(当然可能还有其他更好地解决方法,希望能多提宝贵意见-_-)
例子还是一样:两张表account和degree,使用account_id关联,需要查出两张表的所有纪录

首先:修改实体类,增加以下属性:
        private degree _degree;
        public degree degree
        {
            get
            {
                return _degree;
            }
            set
            {
                _degree = value;
            }
        }(和第三种方法一样)

然后:修改配置文件,这也是最重要的地方(ps:ibatis.net中的配置文件真的很强)
在resultmaps节加入:
    <resultmap id="com2result"  class="account" >
      <result property="id"           column="account_id"/>
      <result property="firstname"    column="account_firstname"/>
      <result property="lastname"     column="account_lastname"/>
      <result property="emailaddress" column="account_email" nullvalue="no_email@provided.com"/>
      <result property="degree"  resultmapping="account.degree-result"/>
    </resultmap>

    <resultmap id="degree-result"  class="degree">
      <result property="id"           column="account_id"/>
      <result property="degreename"    column="degreename"/>
    </resultmap>这里最主要的就是使用了resultmapping属性,resultmapping="account.degree-result",其中account是当前配置文件的namespace:
<sqlmap namespace="account"  ......

在statements节加入:
    <select id="getcom2tables"
     resultmap="com2result">
      select accounts.*, degree.*
      from accounts,degree
      where accounts.account_id = degree.account_id
    </select>这样就可以随心所欲的写自己需要的sql,性能也很好,不会出现第三种方法中的1+n条的查询语句了。

原文地址: http://www.cnblogs.com/firstyi/archive/2007/08/22/864942.html

转载于:https://www.cnblogs.com/zyfking/archive/2009/01/19/1378513.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值