本文源代码下载地址:

  http://flashview.ddvip.com/2009_01/NHibernateDemo.rar

  NHibernate相信大家都已非常熟悉,园子里有很多高手写了相关的系列文章,不过我还是NHibernate的一名初学者,在此将一个晚上学习成果分享一下,一个很简单的利用NHibernate实现增删改的例子。本例中使用的NHibernate版本为版本为官方2008年9月29日最新发布的NHibernate-2.0.1.GA版本,点击下载

  1 首先创建一个数据库NHibernateSample,使用的数据库版本为sqlserver2005。在该数据库中创建表UserInfo。CREATETABLE[dbo].[UserInfo]
(
  [UserInfoID][int]IDENTITY(1,1)NOTNULL,
  [UserName][varchar](20)COLLATEChinese_PRC_CI_ASNULL,
  [Email][varchar](100)COLLATEChinese_PRC_CI_ASNULL
2 打开vs2008,创建web application 命名为Web,解决方案的名称设为NHibernateDemo,然后再此解决方案下添加两个类库项目BLL和Model。

NHibernate入门级示例(增 删 改)

  3 解压下载的NHibernate包,将NHibernate-2.0.1.GA-binbinnet-2.0目录下的dll文件复制到web项目中的DLL文件夹中。DLL文件夹用来存放一些公用的dll文件。

  4 在Model项目中创建两个目录:Entities和Mappings。分别存放实体类和映射文件。

  在Entities目录下创建类UserInfo.cspublicclassUserInfo
{
    publicvirtualintUserInfoID{get;set;}
    publicvirtualstringUserName{get;set;}
    publicvirtualstringEmail{get;set;}
}
需要注意到是实体类中的属性必须加virtual修饰符。

 

  在Mappings目录下创建映射文件UserInfo.hbm.xml

<?xmlversion="1.0"encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
 assembly="Model"namespace="Model">
  <classname="Model.Entities.UserInfo,Model"table="UserInfo">
    <idname="UserInfoID"column="UserInfoID"type="Int32"unsaved-value="0">
      <generatorclass="native"></generator>
    </id>
    <propertyname="UserName"column="UserName"type="string"length="20"not-null="false"/>
    <propertyname="Email"column="Email"type="string"length="100"not-null="false"></property>
  </class>
</hibernate-mapping>

  映射文件创建好后,要修改该文件的输入操作为“嵌入式资源”,默认情况下为内容,在映射文件上右击属性,修改如下:

NHibernate入门级示例(增 删 改)

  5 在BLL项目中创建类UserInfoBLL.cs 用来实现对UserInfo表的增删改操作。在BLL项目中添加对Model和NHibernate的引用

NHibernate入门级示例(增 删 改)

 

  UserInfoBLL.csl类的代码如下:

UserInfoBLL
  public class UserInfoBLL
  {
    private string path = HttpContext.Current.Server.MapPath("~/hibernate.cfg.xml");
  
    public bool Insert(UserInfo userInfo)
    {
      Configuration cfg = new Configuration().Configure(path);
  
      ISession session = cfg.BuildSessionFactory().OpenSession();
      ITransaction transaction = session.BeginTransaction();
  
      try
      {
        session.Save(userInfo);
        transaction.Commit();
        return true;
      }
      catch (Exception e)
      {
        transaction.Rollback();
        return false;
      }
      finally
      {
        session.Close();
      }
    }
  
    public IList<UserInfo> GetUsers()
    {
      Configuration cfg = new Configuration().Configure(path);
      ISession session = cfg.BuildSessionFactory().OpenSession();
  
      //使用HQL
      IList<UserInfo> list = session.CreateQuery(" from UserInfo")
        .List<UserInfo>();
      return list;
    }
  
    public bool Update(UserInfo userInfo)
    {
      Configuration cfg = new Configuration().Configure(path);
  
      ISession session = cfg.BuildSessionFactory().OpenSession();
      ITransaction transaction = session.BeginTransaction();
      try
      {
        session.Update(userInfo);
        transaction.Commit();
        return true;
      }
      catch (Exception e)
      {
        transaction.Rollback();
        return false;
      }
      finally
      {
        session.Close();
      }
    }
  
    public bool Delete(UserInfo userInfo)
    {
      Configuration cfg = new Configuration().Configure(path);
  
      ISession session = cfg.BuildSessionFactory().OpenSession();
      ITransaction transaction = session.BeginTransaction();
      try
      {
        session.Delete(userInfo);
        transaction.Commit();
        return true;
      }
      catch (Exception e)
      {
        transaction.Rollback();
        return false;
      }
      finally
      {
        session.Close();
      }
    }
  
    public UserInfo GetUserInfoById(int userId)
    {
      Configuration cfg = new Configuration().Configure(path);
      ISession session = cfg.BuildSessionFactory().OpenSession();
      return session.Get<UserInfo>(userId);
    }
}

 

  上面的GetUsers方法中用的是HQL查询的数据,NHibernate查询数据的方式有三种,具体参见NHibernate文档。

  5 在web项目的根目录下添加hibernate.cfg.xml文件,该文件用于配置一些数据库连接方面的信息。

<?xmlversion="1.0"encoding="utf-8"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factoryname="NHibernateDemo">
    <propertyname="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <propertyname="connection.connection_string">
      DataSource=.SQLEXPRESS;InitialCatalog=NHibernateSample;
      IntegratedSecurity=True;Pooling=False;uid=sa;pwd=sa123
    </property>
    <propertyname="adonet.batch_size">10</property>
    <propertyname="show_sql">false</property>
    <propertyname="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
    <propertyname="use_outer_join">true</property>
    <propertyname="command_timeout">10</property>
    <propertyname="query.substitutions">true1,false0,yes'Y',no'N'</property>
    <mappingassembly="Model"/>
  </session-factory>
</hibernate-configuration>

 

  6 在web项目中添加Model和BLL的引用。

NHibernate入门级示例(增 删 改)

  接着添加页面User.aspx,前台的现实我们使用repeater控件

<asp:RepeaterID="rptUserInfo"runat="server">
      <HeaderTemplate>
        <tableid="tblUserInfo"border="0"width="100%"cellpadding="0"cellspacing="1">
          <tr>
            <td>
              <inputtype="checkbox"id="chkAll"name="chkAll"value="checkbox"
  
               onclick="checkAll('chkAll',this);"/>
            </td>
            <td>
              用户ID
            </td>
            <td>
              用户名
            </td>
            <td>
              电子邮箱
            </td>
          </tr>
      </HeaderTemplate>
      <ItemTemplate>
        <tr>
          <td>
            <inputtype="checkbox"name="chkSelect"
  
          value ='<%#(Container.DataItemasModel.Entities.UserInfo).UserInfoID%>'
            onclick="checkAll('chkAll',this);"/>
          </td>
          <td>
            <%#(Container.DataItemasModel.Entities.UserInfo).UserInfoID%>
          </td>
          <td>
            <%#(Container.DataItemasModel.Entities.UserInfo).UserName%>
          </td>
          <td>
            <%#(Container.DataItemasModel.Entities.UserInfo).Email%>
          </td>
        </tr>
      </ItemTemplate>
      <FooterTemplate>
        </table>
      </FooterTemplate>
    </asp:Repeater>

 

  后台绑定方法

privatevoidBindInfo()
{
  UserInfoBLLu=newUserInfoBLL();
  IList<Model.Entities.UserInfo>list=u.GetUsers();
  rptUserInfo.DataSource=list;
  rptUserInfo.DataBind();
}

  新增,修改和删除的代码就不一一贴出了,因为比较简单 就是调用UserInfoBLL类中的方法而已,大家可以在下面下载本实例的源码看。

  最后的运行结果

NHibernate入门级示例(增 删 改)

  需要注意的地方:

  1 实体类中的属性要加virtual修饰符。

  2 实体类的映射文件UserInfo.hbm.xml 的生成操作默认为为“Content(内容)”,要将之改为“Embedded Resource(嵌入式资源)”

  3 hibernate.cfg.xml配置文件的connection.connection_string 要修改为自己的连接串。

  终于写完,由于刚接触NHibernate,不好的地方希望大家批评指正,希望对初学NHibernate的朋友有所帮助。

posted on 2009-03-02 13:58  许维光  阅读(234)  评论(0)    收藏  举报