代码改变世界

NHibernate In Action CH2 Hello NHibernate

2011-07-16 16:20  一一九九  阅读(193)  评论(0编辑  收藏  举报

看了一下还是07年写的Blog,想来看NHibernate已经断断续续将近两年了。写的有些凌乱,整理一下。

记录了建立NHibernate Project的步骤:

(一) Set up the Project,add assembly reference

  • 添加引用。在Project中添加Reference: NHibernate.dll
  • Using NHibernate, NHibernate.Cfg。

(二)    Create Employee Class   注意:这里有一个自引用的关系。

public class Employee {
     public virtual int ID { get; set; }
     public virtual string Name { get; set; }
     public virtual Employee Manager { get; set; }
    }

(三) Setting up the database   作者这里使用SQL创建的Database和Table Schema。

(四)Creating an Employee and saving to the database。这个过程和your first application base on NH 差不多。创建一个单例的SessinFactory,获取Session,然后将New出来的Employee通过调用Session的Save保存。

public class EmployeeReporsitory 

    private static ISessionFactory _sessionFactory; 
    public ISessionFactory SessionFactory   { 
        get { 
                   if (_sessionFactory = null) 
                   {  
                          Configuration cfg = new Configuration(); 
                         cfg.AddAssembly(Assembly.GetCallingAssembly());
                          cfg.Configure();
                         _sessionFactory = cfg.BuildSessionFactory();
                     }
     return _sessionFactory;
                  }
             } 
     

public void DoSaveEmployee(Employee employee)  { 
     using(ISession session = SessionFactory.OpenSession()) 
       {
          using (ITransaction tran = session.BeginTransaction())  {
                         session.Save(employee);
                         Tran.commit();
                      } 
        } 
}
作者说“Don't use this OpenSession function in your production projects。You'll learn more economical approaches throught out this book”.

(五) Loading an Employee from the database

public IList<Employee> GetEmployees()  
{
     using (ISession session = SessionFactory.OpenSession()) 
     {  
         IList<Employee> employes = session.CreateQuery("from Employee as emp order by emp.name asc").List<Employee>();
          return employes;
            }
}

(六) Creating a mapping file

<?xml version="1.0"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
    auto-import="true">
<class name="HelloNHibernate.Employee, HelloNHibernate" lazy="false">
<id name="id" access="field">
<generator class="native" />
</id>
<property name="name" access="field" column="name"/>
<many-to-one access="field" name="manager" column="manager"
        cascade="all"/>
</class>
</hibernate-mapping>

作者在这里指定了列名,其实从Your First Application Base on NHibernate 上我们知道这是没有必要的。

作者接下来解释了每个节点的含义。比如说Class节点表示映射到表Employee,也就是类名。Manger属性是个一对多的关系,映射到列MangerID上,估计作者上面写错了,写成了Manger。

(七)Configuring your application  采用的是App.Config的方式

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="nhibernate"
             type="System.Configuration.NameValueSectionHandler, 
             System, Version=1.0.3300.0,Culture=neutral, 
             PublicKeyToken=b77a5c561934e089"
/>
</configSections>
<nhibernate>
<add key="hibernate.show_sql"
         value="false" />
<add key="hibernate.connection.provider"
         value="NHibernate.Connection.DriverConnectionProvider" />
<add key="hibernate.dialect"
         value="NHibernate.Dialect.MsSql2000Dialect" />
<add key="hibernate.connection.driver_class"
         value="NHibernate.Driver.SqlClientDriver" />
<add key="hibernate.connection.connection_string"
         value="Data Source=127.0.0.1; 
  Database=HelloNHibernate;Integrated Security=SSPI;" />
</nhibernate>
</configuration>

说明一下: 在ConfigSections中的配置中NHibernate的Section中采用的配置value的Type的值是NH1.2GA的版本,2.0以后的版本如下:

<configSections>
  <section name="nhibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
</configSections>

说明: 如果是采用DLL Test的方式,而不是WinForm或者Console Exe的方式的话,Hibernate的配置文件不能采用app.config,需要采用单独的hibernate.cfg.xml。因为app.config每个应用程序只有一个,所以不能采用多个,在DLL下不能默认加载App.config文件。