码迷,mamicode.com
首页 > Web开发 > 详细

NHibernate的使用

时间:2015-11-12 17:58:09      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:

编写一个nhibernate的步骤

  1. 首先下载nhibernate(NHibernate.ll、Iesi.Collections.dll)
  2. 搭建三层架构
  3. 编写model,实体,实体类的映射文件(CustomerEntity、CustomerEntity.hbm.xml)

  注意:把CustomerEntity.hbm.xml设置为嵌入的资源

  4.编写Dal(记着引用第一步的dll),并编写SessionManager类

  5.编写业务逻辑

  6.编写视图,首先要编写nhibernate.cfg.xml

注意:把nhibernate.cfg.xml设为始终复制或如果较新则复制

 

CustomerEntity.hbm.xml的内容如下

<?xml version="1.0" encoding="utf-8" ?>

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

  <class name="CustomerEntity" table="Customer">

    <id name="CustomerId">

      <column name="CustomerId" sql-type="int" not-null="true"/>

      <generator class="native"/>

    </id>

    <version name="Version"/>

    <property name="Firstname">

      <column name="Firstname" length="50" not-null="true"/>

    </property>

    <property name="Lastname">

      <column name="Lastname" length="50" not-null="true"/>

    </property>

 

  </class>

 

</hibernate-mapping>

 

 

nhibernate.cfg.xml的内容如下

<?xml version="1.0" encoding="utf-8"?>

<!--

This template was written to work with NHibernate.Test.

Copy the template to your NHibernate.Test project folder and rename it in hibernate.cfg.xml and change it

for your own use before compile tests in VisualStudio.

-->

<!-- This is the System.Data.dll provider for SQL Server -->

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

    <session-factory name="NHibernate.Test">

       <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>

       <property name="connection.connection_string">

      Server=CAOHM;initial catalog=Test;uid=sa;pwd=abc@123;

    </property>

       <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>

    <mapping assembly="Model"/>

    </session-factory>

</hibernate-configuration>

 

SessionManager类的内容如下

public class SessionManager

    {

        private ISessionFactory _sessionFactory;

        public SessionManager()

        {

            _sessionFactory = (new Configuration()).Configure().BuildSessionFactory();

        }

        public ISession GetSession()

        {

            return _sessionFactory.OpenSession();

        }

    }

 

Dal层使用

   public class CustomerDal

    {

        ISession session = null;

        public CustomerDal()

        {

            session = (new SessionManager()).GetSession();

        }

        public void Insert(CustomerEntity customer)

        {

           object obj= session.Save(customer);

        }

      

    }

NHibernate的使用

标签:

原文地址:http://www.cnblogs.com/caohuimingfa/p/4959573.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!