第一次玩Nhibernate
以下所写只为帮助写出第一个Nhibernate程序,罗列注意事项
1. 准备:
Nhibernate的dll文件
Castle.Core.dll
Castle.DynamicProxy2.dll
Iesi.Collections.dll
log4net.dll
NHibernate.dll
将它们引用进程序集
2. 编写实体
代码示例:
---vs08--
Public virtual int Id{set;get;}
Public virtual string name{set;get;}
---vs05—
private Int32 id;
public virtual Int32 Id
{
get { return id; }
set { id = value; }
}
private string sname;
public virtual string Sname
{
get { return sname; }
set { sname = value; }
}
注意:virtual →NHibernate默认使用代理功能,要求持久化类不是sealed的,而且其公共方法、属性和事件声明为virtual。在这里,类中的字段要设置为virtual,否则出现“failed: NHibernate.InvalidProxyTypeException : The following types may not be used as proxies: DomainModel.Entities.Customer: method get_CustomerId should be virtual,method set_CustomerId should be virtual”异常。
3. XML配置文件
命名规范
a--数据库连接XML 以cfg.xml结尾。个人建议命名hibernate.cfg.xml
b-实体映射XML文件,以hbm.xml结尾
XML属性设置
点击xml文件→属性→”复制到输出目录”选择”始终复制”、”生产操作”改为”嵌入资源”
hibernate.cfg.xml→(可复制)
<?xml version="1.0" encoding="utf-8"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">
Data Source=.;Initial Catalog=NHibernate;User ID=sa;Password=123456;
Integrated Security=True;Pooling=False→→连接字符串
</property>
<property name="adonet.batch_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>→→连接驱动→sql为mssql05或者mssql08用此,2000用NHibernate.Dialect.MsSql2000Dialect
<property name="use_outer_join">true</property>
<property name="command_timeout">10</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<mapping assembly="Second"/>→→程序集名称,写错将找不到连接
</session-factory>
</hibernate-configuration>
实体配置文件
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Second " namespace="Second">→→注意名称
<class name =" bolt,Second" table="Bolt">→bolt(定位实体类) Second(namespace) Bolt对应数据库表名
<id name="Id" column="BoltId" type="Int32" unsaved-value="0">→→name(属性名) column(表中字段名)
<generator class ="native"></generator>
</id>
<property name ="boltName" column="BoltName" type="string" length="50" not-null="false"/>
</class>
</hibernate-mapping>
测试程序
ISessionFactory fac = new Configuration().Configure().BuildSessionFactory();
ISession session = fac.OpenSession();
ITransaction tran = session.BeginTransaction();
bolt one=new bolt{ boltName="123" };
session.Save(one);
tran.Commit();
session.Close();
Console.WriteLine("OK");
以上程序旨在提醒第一次玩Nhibernate程序的注意事项,帮助大家写出第一个Nhibernate程序,达到快速入门,其他高深理论,去网上查吧,小弟就不JJYY了(Nhibernate之旅个人感觉很不错)