Life is going......

导航

NHibernate 入门

(纯属学习记录)

https://www.hibernate.org/343.html 上下载个NHibernate release:2.0.1GA  

然后参照 Nhibernat quick start guide(https://www.hibernate.org/362.html)

不做全盘翻译 只把基本步骤和碰到的错误记录

Here are the steps we are going to perform:

  • Create the table to persist the .NET class to.(在数据库建表)
  • Create a .NET class that needs to be persisted.(生成表对应的持久类)
  • Create a mapping file so NHibernate knows how to persist the .NET class' properties(生成隐射XML文件)
  • Create a configuration file for NHibernate to know how to connect to your database(在web.config里建立数据库连接等配置)
  • Use the NHibernate API(用NHibernate类操作数据)

1.建表 SQL如下

use NHibernate
go

CREATE TABLE users (
  LogonID 
nvarchar(20NOT NULL default '0',
  Name 
nvarchar(40default NULL,
  Password 
nvarchar(20default NULL,
  EmailAddress 
nvarchar(40default NULL,
  LastLogon 
datetime default NULL,
  
PRIMARY KEY  (LogonID)
)
go

2.新建C#类库文件 命名NHibernate.Examples
using System;

namespace NHibernate.Examples.QuickStart
{
    
public class User
    {
        
private string id;
        
private string userName;
        
private string password;
        
private string emailAddress;
        
private DateTime lastLogon;


        
public User()
        {
        }

        
public string Id 
        {
            
get { return id; }
            
set { id = value; }
        }

        
public string UserName 
        {
            
get { return userName; }
            
set { userName = value; }
        }

        
public string Password 
        {
            
get { return password; }
            
set { password = value; }
        }

        
public string EmailAddress 
        {
            
get { return emailAddress; }
            
set { emailAddress = value; }
        }

        
public DateTime LastLogon 
        {
            
get { return lastLogon; }
            
set { lastLogon = value; }
        }
        
    }
}

3.映射xml文件(User.xml)

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
    
<class name="NHibernate.Examples.QuickStart.User, NHibernate.Examples" table="users">
        
<id name="Id" column="LogonId" type="String" length="20"> 
            
<generator class="assigned" /> 
        
</id> 
        
<property name="UserName" column="Name" type="String" length="40"/> 
        
<property name="Password" type="String" length="20"/> 
        
<property name="EmailAddress" type="String" length="40"/>
        
<property name="LastLogon" type="DateTime"/>
    
</class>
</hibernate-mapping>
(注意:可以用其他的方法去配置哪个CLASS对应哪个映射XML,这里用最简单的方法,在类的同项目下建个同名的 xml)

 4.配置数据库连接(在webconfig里面配置)

 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  
<configSections>
    
<section
      
name="nhibernate" 
      type
="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
    
/>
  
</configSections>

  
<nhibernate>
    
<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
="Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI"
    
/>
  
</nhibernate>
</configuration>

 5.调用NHibernate类进行插入操作(引用下载Nhibernate里面的Nhibernate.dll,log4net.dll,Iesi.Collections.dll)

using NHibernate.Cfg;
using NHibernate;

            //The Configuration object has knowledge of all the mappings 
            
//   that are going on between .NET classes and the backend database. 
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();

            
//The Configuration object will look through the assembly for any files ending in .hbm.xml.
            
//There are other ways to add the mapping files, but this is probably the easiest.
            
//The other way is to mapping the CLASS and the mapping xml in the web config  
            cfg.AddAssembly("NHibernate.Examples");

            ISessionFactory factory 
= cfg.BuildSessionFactory();
            ISession session 
= factory.OpenSession();
            ITransaction transaction 
= session.BeginTransaction();

            NHibernate.Examples.QuickStart.User user 
= new NHibernate.Examples.QuickStart.User();
            user.Id 
= "2";
            user.LastLogon 
= DateTime.Now;
            user.Password 
= "123456";
            user.UserName 
= "T-Mac";
            user.EmailAddress 
= "t_mac@nba.com";

            
// Tell NHibernate that this object should be saved
            session.Save(user);

            
// commit all of the changes to the DB and close the ISession
            transaction.Commit();
            session.Close();

 

 以上步骤是对的,但是会报Could not find the dialect in the configuration这个错误,这是数据库配置问题 ,

因为这个教程版本是1....的,所以要更改一些东西1.

1.映射xml文件(User.xml) 里面

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">

 换成

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">

 2.数据库配置要改(我用的是sqlserver2005)

<configSections>
        
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler,NHibernate"/>
    
</configSections>
    
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
        
<session-factory>
            
<property name="connection.provider">
        NHibernate.Connection.DriverConnectionProvider
      
</property>
            
<property name="dialect">
        NHibernate.Dialect.MsSql2005Dialect
      
</property>
            
<property name="connection.driver_class">
        NHibernate.Driver.SqlClientDriver
      
</property>
            
<property name="connection.connection_string">
        Data Source=AA\BL;Integrated Security=True; initial catalog=NHibernate
      
</property>
      
<property name="proxyfactory.factory_class">
        NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu
      
</property>

    
</session-factory>
    
</hibernate-configuration>

 

  这样运行会报另外一个错The ProxyFactoryFactory was not configured. 因为没有引用上面那个配置中的工厂类

所以在引用下  Required_For_LazyLoading文件夹下的 LinFu下的NHibernate.ByteCode.LinFu.dll

当然也可以用 Castle 那要改下配置

 

基本上可以运行成功了~

 哦 忘了 要把类里面的那些字段前面全部加上 virtual 修饰符

posted on 2009-06-16 13:03  loaferdeng  阅读(170)  评论(0编辑  收藏  举报