总结一个NHibernate的开发小例子

来源:互联网 发布:淘宝客服添加旺旺账号 编辑:程序博客网 时间:2024/06/12 01:33

总结一个NHibernate的开发小例子

因为空间上用的Access数据库,所以选择了NHibernate.JetDrive驱动
(可以到www.hibernate.org下载,包含在NHibernateContrib的bin中)

1、新建数据库


*注意数据库中不允许使用的字段名。

2、在.net中新建一个Web项目
使用三层结构
WEB      表现层
MODEL    数据层
BLL和DAL 业务逻辑层和数据访问层
DB       存放数据库

将5个文件添加到bin项目文件夹,并添加引用
Castle.DynamicProxy.dll
Iesi.Collections.dll
log4net.dll
NHibernate.dll
NHibernate.JetDriver.dll

3、配置web.config文件Web.config

在<system.web>节点前添加
<configSections>
 <section
  name="nhibernate"
  type= "System.Configuration.NameValueSectionHandler,System,Version=1.1.4322.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"
 />
</configSections>

 <nhibernate>
        <add key="hibernate.show_sql" value="true" />
        <add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
        <add key="hibernate.dialect" value="NHibernate.JetDriver.JetDialect, NHibernate.JetDriver" />
        <add key="hibernate.connection.driver_class" value="NHibernate.JetDriver.JetDriver, NHibernate.JetDriver" />
        <add key="hibernate.connection.isolation" value="ReadCommitted"/>
        <add key="hibernate.connection.connection_string" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/Inetpub/wwwroot/test/DB/eloowdb.mdb" />
</nhibernate>

4、创建映射文件

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
 <class name="test.Model.Info, test" table="info">
  <id name="id" column="id" type="Int32" unsaved-value="0">
   <generator class="identity"/>
  </id>
     <property name="uname" column="uname" type="String" not-null="true" />
     <property name="address" column="address" type="String" not-null="true" />
        </class>
</hibernate-mapping>

在<class name="test.Model.Info, test" table="info">的name中,得一个是类的引用,一个是程序集名。
程序集名可以在test.csproj中查看,AssemblyName = "test"。

5、编写被持久化的类(在MODEL中)
可以使用NHibernateContrib中的hbm2net生成

using System;

namespace test.MODEL
{
 /// <summary>
 /// POJO for Info. This class is autogenerated
 /// </summary>
 [Serializable]
 public class Info
 {
  #region Fields
  
  private Int32 _id;
  private String _uname;
  private String _address;

  #endregion

  #region Constructors
  
  public Info()
  {
  }

  public Info(String _uname, String _address)
    {
     this._uname = _uname;
     this._address = _address;
    }
 
  #endregion
 
  #region Properties

  public Int32 id
  {
   get { return this._id; }
   set { this._id = value; }
  }
  
  public String uname
  {
   get { return this._uname; }
   set { this._uname = value; }
  }
  
  public String address
  {
   get { return this._address; }
   set { this._address = value; }
  }
  
  #endregion
 }
}

6、编写数据访问层的Helper类(在MODEL中)

using System;
using System.Text;
using System.Collections;
using System.Data;

using NHibernate;
using NHibernate.Cfg;
using NHibernate.Engine;

namespace test.MODEL
{
 /// <summary>
 /// NHibernateHelper 的摘要说明。
 /// </summary>
 public class NHibernateHelper
 {
  private NHibernateHelper()
  {
  }
  private static NHibernate.ISessionFactory SessionFactory = null;
  private static string ConfigFileName = null;

  private static ISessionFactory GetSessionFactory()
  {
   if (SessionFactory != null)
   {
    return SessionFactory;
   }
   Configuration Cfg = null;
   try
   {
    if(ConfigFileName != null)
     Cfg = new Configuration().Configure(ConfigFileName);
    else
     Cfg = new Configuration();
   }
   catch (Exception e)
   {
    NHibernate.HibernateException ex = new HibernateException(e);
    throw (ex);
   }
   try
   {
    Cfg.AddAssembly("model");
   }
   catch (Exception e)
   {
    NHibernate.HibernateException ex = new HibernateException(e);
    throw (ex);
   }
   try
   {
    SessionFactory = Cfg.BuildSessionFactory();
    return SessionFactory;
   }
   catch (Exception e)
   {
    NHibernate.HibernateException ex = new HibernateException(e);
    throw (ex);
   }
  }

  private static ISessionFactory GetSessionFactory()
  {
   return GetSessionFactory(null);
  }

  public static string configFileName
  {
   get{return ConfigFileName;}
   set{ConfigFileName = value;}
  }

  public static ISession CurrentSession()
  {
   ISessionFactory SessionFactory = GetSessionFactory();
   try
   {
    ISession Session = SessionFactory.OpenSession();
    return Session;
   }
   catch (Exception e)
   {
    NHibernate.HibernateException ex = new HibernateException(e);
    throw (ex);
   }
  }

  public static void ReloadConfig()
  {
   SessionFactory = null;
  }

  public static System.Collections.IList ExecuteSQL(string query)
  {
   System.Collections.IList result = new ArrayList();

   ISessionFactoryImplementor s = (ISessionFactoryImplementor)GetSessionFactory();
   IDbCommand cmd = s.ConnectionProvider.Driver.CreateCommand();
   cmd.CommandText = query;

   IDbConnection conn = s.OpenConnection();
   try
   {
    cmd.Connection = conn;
    IDataReader rs = cmd.ExecuteReader();

    while (rs.Read())
    {
     int fieldCount = rs.FieldCount;
     object[] values = new Object[fieldCount];
     for (int i = 0; i < fieldCount; i++)
     {
      values[i] = rs.GetValue(i);
     }
     result.Add(values);
    }
   }
   catch (Exception e)
   {
    NHibernate.HibernateException ex = new HibernateException(e);
    throw (ex);
   }
   finally
   {
    s.CloseConnection(conn);
   }
   return result;
  }

  public static void SaveObject(Object obj)
  {
   ISession session = CurrentSession();
   ITransaction tr = session.BeginTransaction();
   try
   {
    session.Save(obj);
    tr.Commit();
   }
   catch (Exception ex)
   {
    tr.Rollback();
    throw (ex);
   }
   finally
   {
    if (session.IsOpen)
    {
     session.Close();
    }
   }
  }

  public static void UpdateObject(Object obj)
  {
   ISession session = CurrentSession();
   ITransaction tr = session.BeginTransaction();
   try
   {
    session.Update(obj);
    tr.Commit();
   }
   catch (Exception ex)
   {
    tr.Rollback();
    throw (ex);
   }
   finally
   {
    if (session.IsOpen)
    {
     session.Close();
    }
   }
  }

  public static void SaveOrUpdateObject(Object obj)
  {
   ISession session = CurrentSession();
   ITransaction tr = session.BeginTransaction();
   try
   {
    session.SaveOrUpdate(obj);
    tr.Commit();
   }
   catch (Exception ex)
   {
    tr.Rollback();
    throw (ex);
   }
   finally
   {
    if (session.IsOpen)
    {
     session.Close();
    }
   }
  }

  public static void DeleteObject(Object obj)
  {
   ISession session = CurrentSession();
   ITransaction tr = session.BeginTransaction();
   try
   {
    session.Delete(obj);
    tr.Commit();
   }
   catch (Exception ex)
   {
    tr.Rollback();
    throw (ex);
   }
   finally
   {
    if (session.IsOpen)
    {
     session.Close();
    }
   }
  }

  public static System.Collections.IList Find(string HQL)
  {
   ISession session = CurrentSession();
   System.Collections.IList list = null;
   try
   {
    list = session.Find(HQL);
   }
   catch (Exception ex)
   {
    throw (ex);
   }
   finally
   {
    if (session.IsOpen)
    {
     session.Close();
    }
   }
   return list;
  }

  public static Object GetObject(Type ClassType, object ID)
  {
   ISession session = CurrentSession();
   object Getobj = null;
   try
   {
    Getobj = session.Get(ClassType, ID);
    return Getobj;
   }
   catch (Exception ex)
   {
    throw (ex);
   }
   finally
   {
    if (session.IsOpen)
    {
     session.Close();
    }
   }
  }

  public static bool ObjExist(Type ClassType, object ID)
  {
   object Getobj = GetObject(ClassType, ID);
   if (Getobj == null)
   {
    return false;
   }
   else
   {
    return true;
   }
  }

  public static bool ObjExist(string query)
  {
   ISessionFactoryImplementor s = (ISessionFactoryImplementor)GetSessionFactory();
   IDbCommand cmd = s.ConnectionProvider.Driver.CreateCommand();
   cmd.CommandText = query;

   IDbConnection conn = s.OpenConnection();
   try
   {
    cmd.Connection = conn;
    IDataReader rs = cmd.ExecuteReader();

    if(rs.Read())
     return true;
    else
     return false;
   }
   catch (Exception e)
   {
    NHibernate.HibernateException ex = new HibernateException(e);
    throw (ex);
   }
   finally
   {
    s.CloseConnection(conn);
   }
  }
 }
}

在Cfg.AddAssembly("model");加栽程序集
因为在Web.config已经配置,因此不需要再创建Hiberner.config.xml

7、编写数据访问层(在DAL中)

using System;

using test.MODEL;

namespace eloow.DAL
{
 public class InfoDAL
 {
  public InfoDAL()
  {
  }

  public void addInfo(Info a)
  {
   NHibernateHelper.SaveObject(a);
  }

  public void updateInfo(Info a)
  {
   NHibernateHelper.UpdateObject(a);
  }

  public void daleteInfo(Info a)
  {
   NHibernateHelper.DeleteObject(a);
  }

  public void getInfo(Info a)
  {
   NHibernateHelper.GetObject(a.GetType(), a.id);
  }

  public bool InfoExist(string HQL)
  {
   return NHibernateHelper.ObjExist(HQL);
  }
 }
}

8、编写业务逻辑层(在BLL中)

using System;

using test.DAL;
using test.MODEL;

namespace test.BLL
{
 public class InfoBLL
 {
  public InfoBLL()
  {
  }

  public bool InfoExist(string uname, string address)
  {
   InfoDAL ad = new InfoDAL();
   return ad.AccountExist("select * from account where uname=/"" + username + "/" and address=/"" + address + "/"");
  }

  public void addInfo(string uname, string address)
  {
   InfoDAL ad = new InfoDAL();
   Info a = new Info();

   a.uname = regDate;
   a.address = username;

   ad.addInfo(a);
  }
 }
}

8、实现表现层(在WEB中)

(未完……) 

原创粉丝点击