學習MyBatis.Net之路 (三)

11接下來我們看看我們多表聯合查詢,動態SQl拼接,以及SQL片段的使用,我們這裏用到上面的PersonAndCour.cs這個自定義類
我們先添加PersonAndCourse.xml這個映射文件

<?xml version="1.0" encoding="utf-8" ?>
<sqlMap namespace="PratiseMyBatis" xmlns="http://ibatis.apache.org/mapping"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <alias>
    <!--類的別名-->
    <typeAlias alias="PersonAndCourse" type="PratiseMyBatis.Models.PersonAndCourse,PratiseMyBatis"  />
  </alias>


  <resultMaps>
    <!--PersonAndCourse類和DB類的映射-->
    <resultMap id="PersonAndCourseResult" class="PersonAndCourse">
      <result property="ID" column="ID"/>
      <result property="Name" column="Name"/>
      <result property="Age" column="Age"/>
      <result property="Sex" column="Sex"/>
      <result property="CourseName" column="CourseName"/>
    </resultMap>
  </resultMaps>



  <statements>

    <!--可以重複使用的sql語句-->
    <sql id="testSql">
      select p.Id,p.Name,p.Age,p.Sex,c.CourseName from Person p inner join Course c on p.ID=c.PerID
    </sql>

    <select id="GetList1" resultMap="PersonAndCourseResult">
      select p.Id,p.Name,p.Age,p.Sex,c.CourseName from Person p inner join Course c on p.ID=c.PerID
    </select>

    <!--多條件查詢-->
    <select id="GetList2" parameterClass="PersonAndCourse" resultMap="PersonAndCourseResult">
      select p.Id,p.Name,p.Age,p.Sex,c.CourseName from Person p inner join Course c on p.ID=c.PerID
        <dynamic prepend="where">
          <!--姓名不能爲空-->
          <isNotEmpty property="Name" prepend="And">
            p.Name=#Name#
          </isNotEmpty>
          <!--年齡大於零-->
          <isGreaterThan property="Age" prepend="And" compareValue="0">
            p.Age=#Age#
          </isGreaterThan>
        </dynamic>
    </select>

    <select id="GetList3" resultMap="PersonAndCourseResult">
      <!--使用重複的sql語句-->
      <include refid="testSql"/>
    </select>


    <insert id="Add1" parameterClass="System.Collections.IDictionary" resultClass="Int32" >
      Begin try
      Begin tran
      declare @id int 
      set @id=(select Top 1 ID from Person)
      Update Person Set Name='sasa' where ID=@id
      insert into Person Values(#Name#,#Age#,#Sex#)
      delete Course where ID=15
      <selectKey property="ID" resultClass="int" type="post">
        select @@Identity as ID   
      </selectKey>
      Commit tran
      End  try
      Begin Catch
      ROLLBACK TRAN
      END CATCH      
    </insert>

  </statements>

</sqlMap>

控制器代碼

    //var list1 = BaseDA.QueryForList<PersonAndCourse>("GetList1",null);    //聯合查詢所有數據
            var list2 = BaseDA.QueryForList<PersonAndCourse>("GetList2", new PersonAndCourse() { Name = "sasa", Age = 15 });      //多條件查詢
            var  list3 = BaseDA.QueryForList<PersonAndCourse>("GetList3", null);      //使用重複使用的sql語句

A:     先說下SQL片段,我們在查詢分頁時的查詢拼接條件或都其他查詢時,可能同一段代碼重複使用,這時我們就可以利用SQL片段,把重利利用的SQL代碼提取出來,如PersonAndCour.xml裏一樣,這樣我們用這一句就可以引用上面的SQL語句,這裏的refid就是SQl片段中id的名字

B:     再說說多條件查詢時動態拼接SQl語句,如下圖
這裏寫圖片描述

這裏我們傳入的參數是PersonAndCourse,輸出的參數也是這個, 這個參數我們也可以自己定義,需要幾個字段就定義幾個字段,但在這裏時要寫全名比如:parameterClass=”MyBatisNet.EntityModel.whereModel”,還有之前在博客園找到的動態SQL拼接的都是JAVA目錄,進而是直接用標籤嵌套標籤,我在項目中也使用這種方式,但是標籤的裏的語句就是不執行,最後在網上找了好多,最後發現用標籤之後裏面的語句就可以拼接成功了,原因現在還不知道,那位大神知道可以告知下,標籤裏面的判斷條件整理了如下幾個類型:

特別聲明:因爲標籤寫不出來

在博客上<isPropertyAvailable> 這樣子標籤展示不出來 所以寫成<>isPropertyAvailable       希望大家可以理解
所以  <標籤>   改爲這樣子寫 <>標籤   

一元條件元素: 一元條件元素檢查屬性的狀態是否符合特定的條件。
屬性:
prepend—-可被覆蓋的SQL語句組成呢部分,添加在語句前面(可選)
property—-被比較的屬性(必選)

標籤 含義
<>isPropertyAvailable 檢查是否存在該屬性(存在parameter bear的屬性)
<>isNotPropertyAvailable 檢查是否不存在該屬性(不存在parameter bear的屬性)
<>isNull 檢查屬性是否Null
<>isNotNull 檢查屬性是否不爲Null
<>isEmpty 檢查Collection.size()得值。屬性的String或String.valueOf()的值,是否爲Null或爲空
<>isNotEmpty 檢查Collection.size()得值。屬性的String或String.valueOf()的值,是否不爲Null或爲空
小例子:
<isNotEmpty prepend="And" property="firstName">
    First_Name=#FirstName#
</isNotEmpty>

二元條件元素: 將一個屬性值和靜態值或另一個屬性值比較,如果條件爲真,元素將被包容在查詢SQL語句中。
屬性:
prepend—-可被覆蓋的SQL語句組成呢部分,添加在語句前面(可選)
property—-被比較的屬性(必選)
compareProerty—-另一個用於和前者比較的屬性(必選或者選擇compareValue)
compareValue—–用於比較的值(必選或選擇compareProperty)

標籤 含義
<>isEqual 比較屬性值和靜態值或另一個屬性值是否相等
<>isNotEqual> 比較屬性值和靜態值或另一個屬性值是否不相等
<>isGreaterThan 比較屬性值是否大於靜態值或另一個屬性值
<>isGreaterEqual 比較屬性值是否大於等於靜態值或另一個屬性值
<>isLessThan 比較屬性值是否小於靜態值或另一個屬性值
<>isLessEqual 比較屬性值是否小於等於靜態值或另一個屬性值

小例子:

<isLessEqual prepend="And" property="age" comparevalue="18">
    ADOLESCENT = 'TRUE'
</isLessEqual>

其他元素條件
parameter Present: 這些元素檢查參數對象是否存在
Parameter Present條件的屬性
prepend - 可被覆蓋的SQL語句組成部分。 添加在語句的前面(可選)

<>isParameterPresent 檢查是否存在參數對象(不爲Null)
<>isNotParameterPresent 例子: <isNotParameterPresent prepend="AND"> Empolyee='default' </isNotParameterPresent>

**iterate: 這屬性遍歷整個集合,併爲List集合中的元素重複元素體的內容。
屬性:**
prepend—-可被覆蓋的SQL語句組成呢部分,添加在語句前面(可選)
property—-類型爲Java.util.List的用於遍歷的元素(必選)
open —-整個遍歷內容體開始的字符串用於定義括號(可選)
close —-每次便利內容之間的字符串,用於定義AND或OR(可選)
便利類型爲java.util.List的元素.
<>iterate

    <iterate prepend="And" property="userNameList" open="(" close=")" conjunction="OR">
                    username=#userNameList[]#   </iterate>

注意:使用時,在List元素名後面包括方括號[]非常重要,方括號[]將對象標記爲List,以防解析器簡單的將List輸出成String

12最後說一下自己嘗試的事務,如果大家有更好的建議可以提出來大家一起分享

第一個方法 就是在PersonAndCourse.Xml裏寫的Sql語句的事務。
這裏寫圖片描述

第二個方法映射文件的中還是單一的條插入SQL語句,我們在控制器中使用事務,如下:

    //事務
        public void Add() 
        {
            ISqlMapper map = Mapper.Instance();
            bool flag = false;
            if (map != null)
            {
                map.BeginTransaction();
                try
                {
                    Person p1 = new Person();
                    p1.ID = 1;
                    p1.Name = "張四";
                    p1.Age = 15;
                    p1.Sex = "女";
                    flag = (int)map.Update("Update",p1)>0;
                    Person p2 = new Person();
                    p2.Name = "李大眼";
                    p2.Age = 37;
                    p2.Sex = "男";
                    flag = (int)map.Insert("Add",p2)>0;
                    if (flag)
                    {
                        map.CommitTransaction();
                    }
                    else 
                    {
                        map.RollBackTransaction();
                    }
                }
                catch (Exception ex)
                {
                    map.RollBackTransaction();                   
                } 
            }          
        }

好了,到這裏功能大致都可以完成了,接下來是Log4net配置的問題了。

修改web.config,主要是配置log4net,參考下面的內容:
需要加載多個DLL

這裏寫圖片描述

<?xml version="1.0"?>
  <configuration>
     <configSections>
          <sectionGroup name="iBATIS">
              <section name="logging" type="IBatisNet.Common.Logging.ConfigurationSectionHandler, IBatisNet.Common"/>
          </sectionGroup>
          <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
      </configSections>
      <system.web>
         <compilation debug="true" targetFramework="4.0"/>
     </system.web>
     <iBATIS>
         <logging>
             <logFactoryAdapter type="IBatisNet.Common.Logging.Impl.Log4NetLoggerFA, IBatisNet.Common.Logging.Log4Net">
                 <arg key="configType" value="inline"/>
                 <arg key="showLogName" value="true"/>
                 <arg key="showDataTime" value="true"/>
                 <arg key="level" value="ALL"/>
                 <arg key="dateTimeFormat" value="yyyy/MM/dd HH:mm:ss:SSS"/>
             </logFactoryAdapter>
         </logging>
     </iBATIS>
     <log4net>
         <!-- Define some output appenders -->
         <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
             <param name="File" value="mybatis.log"/>
             <param name="AppendToFile" value="true"/>
             <param name="MaxSizeRollBackups" value="2"/>
             <param name="MaximumFileSize" value="100KB"/>
             <param name="RollingStyle" value="Size"/>
             <param name="StaticLogFileName" value="true"/>
             <layout type="log4net.Layout.PatternLayout">
                 <param name="Header" value="[Header]\r\n"/>
                 <param name="Footer" value="[Footer]\r\n"/>
                 <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n"/>
             </layout>
         </appender>
         <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
             <layout type="log4net.Layout.PatternLayout">
                 <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] &lt;%X{auth}&gt; - %m%n"/>
             </layout>
         </appender>
         <!-- Set root logger level to ERROR and its appenders -->
         <root>
             <level value="DEBUG"/>
             <appender-ref ref="RollingLogFileAppender"/>
             <appender-ref ref="ConsoleAppender"/>
         </root>
         <!-- Print only messages of level DEBUG or above in the packages -->
         <logger name="IBatisNet.DataMapper.Configuration.Cache.CacheModel">
             <level value="DEBUG"/>
         </logger>
         <logger name="IBatisNet.DataMapper.Configuration.Statements.PreparedStatementFactory">
             <level value="DEBUG"/>
         </logger>
         <logger name="IBatisNet.DataMapper.LazyLoadList">
             <level value="DEBUG"/>
         </logger>
         <logger name="IBatisNet.DataAccess.DaoSession">
             <level value="DEBUG"/>
         </logger>
         <logger name="IBatisNet.DataMapper.SqlMapSession">
             <level value="DEBUG"/>
         </logger>
         <logger name="IBatisNet.Common.Transaction.TransactionScope">
             <level value="DEBUG"/>
         </logger>
         <logger name="IBatisNet.DataAccess.Configuration.DaoProxy">
             <level value="DEBUG"/>
         </logger>
     </log4net>
 </configuration>

好了,大功告成,如果有誰還有不懂的地方,歡迎交流

發佈了44 篇原創文章 · 獲贊 21 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章