使用IBatisNet對NText類型的欄位插入超長文本

來源:互聯網
上載者:User
 

使用IBatisNet當對NText類型的欄位插入超長的文本時,報錯誤"當前命令發生了嚴重錯誤。應放棄任何可能產生的結果"

查了一下資料,當使用具名引數式sql語句時,對於NText類型的參數,如指定length,則可避免上面的問題,
但IBatisNet的resultMap的property裡只有dbType而沒有length,不知為何不提供? NHibernate裡就有類似length的屬性。

不過property裡提供了一個typeHandler,typeHandler是一個Type處理的擴充點,下面我們來看看如何使用它。

1. 類別處理實現
 public class NTextTypeHandler : ITypeHandlerCallback
 {
  #region ITypeHandlerCallback 成員

  public object ValueOf(string s)
  {
   return s;
  }

  public object GetResult(IResultGetter getter)
  {
   if(getter!=null)
    return getter.Value.ToString();
   return "";
  }

  public void SetParameter(IParameterSetter setter, object parameter)
  {
   if(parameter==null)
   {
    setter.Value="";
   }
   else
   {
    // 設定Parameter的其它屬性,本例為size.
    ((SqlParameter)setter.DataParameter).Size = int.MaxValue;
    setter.Value = parameter;
   }
  }

  #endregion
 }

2. resultMap定義
  <resultMap id="InfoResult" class="Info">
   <result property="InfoID" column="infoId"/>
   <result property="Title" column="title"/>
   <result property="Author" column="author"/>
   <result property="Keywords" column="keywords" />
   <result property="PubDate" column="pubDate"/>
   <result property="Content" column="content" dbtype="NText" typeHandler="NTextTypeHandler" />
  </resultMap>

3. statement定義
  <insert id="InsertInfo" parameterClass="Info">
   INSERT INTO infos (title, author, pubDate, keywords, content)
    VALUES (#Title#, #Author#, #PubDate#, #Keywords#, #Content,handler=NTextTypeHandler#)
   <selectKey resultClass="int" type="post" property="InfoID">
    select SCOPE_IDENTITY()
   </selectKey>
  </insert>

在sql語句裡一定要用 #Content, handler=xxx# 的方式來指定,如不指定則在resultMap裡的設定是不起作用的,感覺這兩片定義應該有個地方是多餘的,等有時間再說了。

總結,IBatisNet提供的TypeHandler提供了一個靈活且簡單的類型處理機制。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.