Nhibernate基本

根据以前使用hibernate的经验搭建nhibernate


1.配置sessionfactory(hibernate.cfg.xml)指定数据库连接串,方言,连接池和Mapping文件位置

<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" ><!--此处版本号要和mapping文件中照应-->
<session-factory name="NHibernate.Test">
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">
Server=.;initial catalog=testDB;Integrated Security=True
</property>
<property name="adonet.batch_size">10</property>
<property name="show_sql">false</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="command_timeout">60</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<mapping assembly="NHibernateTest" resource="NHibernateTest.Mapping.PartMapping.hbm.xml" /><!--assembly指定工程名-->
<mapping assembly="NHibernateTest" resource="NHibernateTest.Mapping.UserMapping.hbm.xml" />
</session-factory>
</hibernate-configuration>


2.指定实体类(POCO)

//需要映射的实体类必须全部指定为virtual
public class Part
{
public virtual string PartID { get; set; }
public virtual string PartName { get; set; }
public virtual ISet<User> UserSet { get; set; }//此处映射使用的ISet是hibernate的:Iesi.Collections.Generic.ISet
}


public class User
{
public virtual string UserID { get; set; }
public virtual string UserName { get; set; }
public virtual Part Part { get; set; }
}


3.Mapping

<!--Part.hbm.xml-->
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly
="NHibernateTest"
namespace
="NHibernateTest.Entity">
<class name="Part" table="Parts">
<id name="PartID" column="PartID">
<generator class ="native"/>
</id>
<property name="PartName" column="PartName"></property>
<set name="UserSet" table="Users">
<key column="PartID" foreign-key="FK_UserPart"></key>
<one-to-many class="User"/><!--Many-to-One映射默认是在one端维护-->
</set>
</class>
</hibernate-mapping>

<!--User.hbm.xml-->
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly
="NHibernateTest"
namespace
="NHibernateTest.Entity"><!--指定namespace后在以后指示class的时候可以省略namespace-->
<class name="User" table="Users">
<id name="UserID" column="UserID">
<generator class ="native"/>
</id>
<property name="UserName" column="UserName"/>
<many-to-one name="Part" column="PartID" class="Part" foreign-key="FK_UserPart"></many-to-one>
</class>
</hibernate-mapping>



posted @ 2011-09-28 12:20  wangking1029  阅读(1916)  评论(1编辑  收藏  举报