且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-09-13 08:20:28

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

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

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

首先:修改实体类,增加以下属性:
IBatis.Net学习笔记六--再谈查询        private Degree _degree;
IBatis.Net学习笔记六--再谈查询        
public Degree Degree
IBatis.Net学习笔记六--再谈查询        
{
IBatis.Net学习笔记六--再谈查询            
get
IBatis.Net学习笔记六--再谈查询            
{
IBatis.Net学习笔记六--再谈查询                
return _degree;
IBatis.Net学习笔记六--再谈查询            }

IBatis.Net学习笔记六--再谈查询            
set
IBatis.Net学习笔记六--再谈查询            
{
IBatis.Net学习笔记六--再谈查询                _degree 
= value;
IBatis.Net学习笔记六--再谈查询            }

IBatis.Net学习笔记六--再谈查询        }
(和第三种方法一样)

然后:修改配置文件,这也是最重要的地方(PS:IBatis.Net中的配置文件真的很强)
resultMaps节加入:
IBatis.Net学习笔记六--再谈查询    <resultMap id="com2result"  class="Account" >
IBatis.Net学习笔记六--再谈查询      
<result property="Id"           column="Account_ID"/>
IBatis.Net学习笔记六--再谈查询      
<result property="FirstName"    column="Account_FirstName"/>
IBatis.Net学习笔记六--再谈查询      
<result property="LastName"     column="Account_LastName"/>
IBatis.Net学习笔记六--再谈查询      
<result property="EmailAddress" column="Account_Email" nullValue="no_email@provided.com"/>
IBatis.Net学习笔记六--再谈查询      
<result property="Degree"  resultMapping="Account.Degree-result"/>
IBatis.Net学习笔记六--再谈查询    
</resultMap>
IBatis.Net学习笔记六--再谈查询
IBatis.Net学习笔记六--再谈查询    
<resultMap id="Degree-result"  class="Degree">
IBatis.Net学习笔记六--再谈查询      
<result property="Id"           column="Account_ID"/>
IBatis.Net学习笔记六--再谈查询      
<result property="DegreeName"    column="DegreeName"/>
IBatis.Net学习笔记六--再谈查询    
</resultMap>
这里最主要的就是使用了resultMapping属性,resultMapping="Account.Degree-result",其中Account是当前配置文件的namespace:
<sqlMap namespace="Account"  ......


statements节加入:
IBatis.Net学习笔记六--再谈查询    <select id="GetCom2Tables"
IBatis.Net学习笔记六--再谈查询     resultMap
="com2result">
IBatis.Net学习笔记六--再谈查询      select Accounts.
*, Degree.*
IBatis.Net学习笔记六--再谈查询      from Accounts,Degree
IBatis.Net学习笔记六--再谈查询      where Accounts.Account_ID 
= Degree.Account_ID
IBatis.Net学习笔记六--再谈查询    
</select>

这样就可以随心所欲的写自己需要的sql,性能也很好,不会出现第三种方法中的1+n条的查询语句了。


    本文转自永春博客园博客,原文链接:http://www.cnblogs.com/firstyi/archive/2007/08/22/864942.html,如需转载请自行联系原作者