1、链接配置

 <?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory name="Test">
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Server=.;initial catalog=TestNHibernate;User Id=sa;Password=Hello1234</property>
<property name="adonet.batch_size"></property>
<property name="show_sql">true</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="use_outer_join">true</property>
<property name="command_timeout"></property>
<property name="query.substitutions">true , false , yes 'Y', no 'N'</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<mapping assembly="TestDomain" />
</session-factory>
</hibernate-configuration>

hibernate.cfg.xml

2、构建一个Session管理类,用于管理Session

     internal class SessionManager
{
private ISessionFactory _sessionFactory;
public SessionManager()
{
_sessionFactory = GetSessionFactory();
}
private ISessionFactory GetSessionFactory()
{
return (new Configuration()).Configure().BuildSessionFactory();
}
public ISession GetSession()
{
return _sessionFactory.OpenSession();
}
}

SessionManager

3、构建仓储基类,以便继承

     public class BaseRespository<TEntity>
where TEntity : class,new()
{
protected ISession session;
public ISession Session
{
set
{
session = value;
}
} #region
public BaseRespository()
{
session = (new SessionManager()).GetSession();
}
#endregion public void Create(TEntity dto)
{
CreateTransaction(dto);
} public int CreateAndReturn(TEntity dto)
{
return CreateTransaction(dto);
} public int CreateTransaction(TEntity dto)
{
using (ITransaction tx = session.BeginTransaction())
{
try
{
int newId = (int)session.Save(dto);
session.Flush();
tx.Commit();
return newId;
}
catch (HibernateException)
{
tx.Rollback();
throw;
}
}
} public void Update(TEntity dto)
{
session.Update(dto);
session.Flush();
} public void SaveOrUpdate(IList<TEntity> dtos)
{
foreach (var c in dtos)
{
session.SaveOrUpdate(c);
}
session.Flush();
} public void Delete(TEntity dto)
{
session.Delete(dto);
session.Flush();
} public TEntity GetById(object entityId)
{
return this.session.Get<TEntity>(entityId);
} public IList<TEntity> GetListByExample(TEntity entity)
{
return this.session.CreateCriteria(typeof(TEntity))
.Add(Example.Create(entity)
.IgnoreCase()
.EnableLike()
.SetEscapeCharacter('&')
).List<TEntity>();
} public IList<TEntity> List()
{
return session.CreateCriteria(typeof(TEntity)).List<TEntity>();
} public IList<TEntity> List(params ICriterion[] expression)
{
ICriteria query = session.CreateCriteria(typeof(TEntity));
foreach (ICriterion express in expression)
{
query.Add(express);
}
return query.List<TEntity>();
} public IList<TResult> Select<TResult>(Func<TEntity, TResult> express)
{
return session.CreateCriteria(typeof(TEntity)).List<TEntity>().Select(express).ToList();
}
}

BaseRespository

4、创建领域实体对象

     public class Blogcategory
{
public Blogcategory() { }
public virtual int Cateid { get; set; }
public virtual IList<Blogarticle> Blogarticles { get; set; }
public virtual string Catename { get; set; }
public virtual int Parentid { get; set; }
public virtual int State { get; set; }
public virtual int Sortid { get; set; }
public virtual int Articlecount { get; set; }
public virtual System.DateTime Createtime { get; set; }
public virtual string Note { get; set; }
}

Blogcategory

     public class Blogarticle
{
public Blogarticle() { }
public virtual int Articleid { get; set; }
public virtual Blogcategory Blogcategory { get; set; }
public virtual IList<Blogcomment> Blogcomments { get; set; }
public virtual IList<Blogdigg> Blogdiggs { get; set; }
public virtual string Title { get; set; }
public virtual string Content { get; set; }
public virtual string Description { get; set; }
public virtual string Imageurl { get; set; }
public virtual string Tag { get; set; }
public virtual int Hits { get; set; }
public virtual bool Istop { get; set; }
public virtual int State { get; set; }
public virtual System.Nullable<int> Userid { get; set; }
public virtual string Username { get; set; }
public virtual string Userip { get; set; }
public virtual System.DateTime Createtime { get; set; }
public virtual System.DateTime Publishtime { get; set; }
public virtual System.DateTime Updatetime { get; set; }
public virtual string Note { get; set; }
}

Blogarticle

     public class Blogcomment
{
public Blogcomment() { }
public virtual int Autoid { get; set; }
public virtual Blogarticle Blogarticle { get; set; }
public virtual string Title { get; set; }
public virtual System.Nullable<int> Userid { get; set; }
public virtual string Username { get; set; }
public virtual string Content { get; set; }
public virtual System.DateTime Createtime { get; set; }
public virtual string Ip { get; set; }
public virtual int State { get; set; }
public virtual System.Nullable<int> Verifyuserid { get; set; }
public virtual string Verifyuseraccount { get; set; }
}

Blogcomment

     public class Blogdigg
{
public Blogdigg() { }
public virtual int Autoid { get; set; }
public virtual Blogarticle Blogarticle { get; set; }
public virtual string Diggname { get; set; }
public virtual int Surpporttype { get; set; }
public virtual int State { get; set; }
public virtual string Ip { get; set; }
public virtual System.DateTime Createtime { get; set; }
}

Blogdigg

5、映射文件配置

 <?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping assembly="TestDomain" namespace="TestDomain" xmlns="urn:nhibernate-mapping-2.2" default-lazy="false">
<class name="Blogcategory" table="BlogCategory">
<id name="Cateid" column="CateID">
<generator class="native" />
</id>
<property name="Catename" column="CateName" />
<property name="Parentid" column="ParentID" />
<property name="State" column="State" />
<property name="Sortid" column="SortID" />
<property name="Articlecount" column="ArticleCount" />
<property name="Createtime" column="CreateTime" />
<property name="Note" column="Note" />
</class>
</hibernate-mapping>

Blogcategory.hbm.xml

 <?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping assembly="TestDomain" namespace="TestDomain" xmlns="urn:nhibernate-mapping-2.2" default-lazy="false">
<class name="Blogarticle" table="BlogArticle">
<id name="Articleid" column="ArticleID">
<generator class="native" />
</id>
<many-to-one name="Blogcategory" column="BlogCategory_CateID" />
<property name="Title" column="Title" />
<property name="Content" column="Content" />
<property name="Description" column="Description" />
<property name="Imageurl" column="ImageUrl" />
<property name="Tag" column="Tag" />
<property name="Hits" column="Hits" />
<property name="Istop" column="IsTop" />
<property name="State" column="State" />
<property name="Userid" column="UserID" />
<property name="Username" column="UserName" />
<property name="Userip" column="UserIP" />
<property name="Createtime" column="CreateTime" />
<property name="Publishtime" column="PublishTime" />
<property name="Updatetime" column="UpdateTime" />
<property name="Note" column="Note" />
</class>
</hibernate-mapping>

Blogarticle.hbm.xml

 <?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping assembly="TestDomain" namespace="TestDomain" xmlns="urn:nhibernate-mapping-2.2">
<class name="Blogcomment" table="BlogComment" lazy="false" >
<id name="Autoid" column="AutoID">
<generator class="native" />
</id>
<many-to-one name="Blogarticle" column="BlogArticle_ArticleID" />
<property name="Title" column="Title" />
<property name="Userid" column="UserID" />
<property name="Username" column="UserName" />
<property name="Content" column="Content" />
<property name="Createtime" column="CreateTime" />
<property name="Ip" column="IP" />
<property name="State" column="State" />
<property name="Verifyuserid" column="VerifyUserID" />
<property name="Verifyuseraccount" column="VerifyUserAccount" />
</class>
</hibernate-mapping>

Blogcomment.hbm.xml

 <?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping assembly="TestDomain" namespace="TestDomain" xmlns="urn:nhibernate-mapping-2.2">
<class name="Blogdigg" table="BlogDigg" lazy="false" >
<id name="Autoid" column="AutoID">
<generator class="native" />
</id>
<many-to-one name="Blogarticle" column="BlogArticle_ArticleID" />
<property name="Diggname" column="DiggName" />
<property name="Surpporttype" column="SurpportType" />
<property name="State" column="State" />
<property name="Ip" column="IP" />
<property name="Createtime" column="CreateTime" />
</class>
</hibernate-mapping>

Blogdigg.hbm.xml

6、构建仓储类

     public class BlogCategoryRespository : BaseRespository<Blogcategory>
{ }
public class BlogArticleRespository : BaseRespository<Blogarticle>
{ }

7、测试

     class Program
{
static void Main(string[] args)
{
BlogCategoryRespository target = new BlogCategoryRespository();
Blogcategory dto = new Blogcategory(); dto.Catename = "Test" + new Random().Next(, ).ToString();
dto.Parentid = ;
dto.State = ;
dto.Createtime = DateTime.Now; int newid = target.CreateAndReturn(dto); Blogcategory model = target.GetById();
if (model != null)
{
model.Catename = "newCatename";
target.Update(model);
} model = target.GetById();
if (model != null)
{
target.Delete(model);
} Console.WriteLine(newid);
Console.Read();
}
}

NHibernate下载地址:

  1. http://sourceforge.net/projects/nhibernate/
  2. http://www.nuget.org/packages/NHibernate/
  3. http://hibernate.org/

NHibernate参考手册:NHibernate.chm.rar

Nhibernate基本的增删改查实践的更多相关文章

  1. 大数据系列之分布式数据库HBase-0.9.8安装及增删改查实践

    若查看HBase-1.2.4版本内容及demo代码详见 大数据系列之分布式数据库HBase-1.2.4+Zookeeper 安装及增删改查实践 1. 环境准备: 1.需要在Hadoop启动正常情况下安 ...

  2. 大数据系列之分布式数据库HBase-1.2.4+Zookeeper 安装及增删改查实践

    之前介绍过关于HBase 0.9.8版本的部署及使用,本篇介绍下最新版本HBase1.2.4的部署及使用,有部分区别,详见如下: 1. 环境准备: 1.需要在Hadoop[hadoop-2.7.3]  ...

  3. Mybatis连接Oracle实现增删改查实践

    1. 首先要在项目中增加Mybatis和Oracle的Jar文件 这里我使用的版本为ojdbc7 Mybatis版本为:3.2.4 2. 在Oracle中创建User表 create table T_ ...

  4. 一个使用MVC3+NHibernate “增删改查” 的项目

    一个使用MVC3+NHibernate “增删改查” 的项目  前言: 谈到NHibernate大伙并不陌生,搞Java的更是清楚,Hibernate是一个目前应用的最广泛的开放源代码的对象关系映射框 ...

  5. MVC项目实践,在三层架构下实现SportsStore-11,使用Knockout实现增删改查

    SportsStore是<精通ASP.NET MVC3框架(第三版)>中演示的MVC项目,在该项目中涵盖了MVC的众多方面,包括:使用DI容器.URL优化.导航.分页.购物车.订单.产品管 ...

  6. 【C#】使用NHibernate连接MySQL数据库及增删改查

    学习资料 http://www.sikiedu.com/course/51/task/891/show https://www.codeproject.com/Articles/26123/NHibe ...

  7. NHibernate初学一之简单增删改查

    以前有简单了解NHibernate,但因项目一直没有运用所以也没有机会进行一个详细了解:最近利用一点空闲的时间认真学习它:同样希望把学习过程进行简单记录,今天简单写一个针对MSSQL数据库的增删改查的 ...

  8. 一个使用MVC3+NHibernate “增删改查” 的项目(修正版)

      前言: 谈到NHibernate大伙并不陌生,搞Java的更是清楚,Hibernate是一个目前应用的最广泛的开放源代码的对象关系映射框架,它对Java的JDBC(类似于ADO.Net)进行了非常 ...

  9. 使用NHibernate连接MySQL数据库及增删改查

    学习资料 http://www.sikiedu.com/course/51/task/891/show https://www.codeproject.com/Articles/26123/NHibe ...

随机推荐

  1. 课时5.什么是URL(理解)

    其实浏览器的地址栏中输入的地址就是一个URL. http://127.0.0.1/index.html(浏览器会自动添加:80) http://127.0.0.1:80/index.html(这是浏览 ...

  2. PHP判断时关于null,0,true,flase的值

    <?php// $wh = 0; //等于整数0,等于字符串'0',等于空字符串,等于空格字符串, 等于空(null),等于字符串('null')// $wh = '0'; //=>等于整 ...

  3. django-simple-captcha 验证码干扰线随机点位

    CAPTCHA_NOISE_FUNCTIONS = ( 'captcha.helpers.noise_null',# 设置样式 'captcha.helpers.noise_arcs',# 设置干扰线 ...

  4. python编写定时执行脚本

    前几天在抓博客园文章,打算每天抓10条最新的,所以就在脚本中加了定时让它在每天凌晨四点中时执行,但是昨天发现,报错了: 显示是远程主机强制关闭了一个链接, 原因是:mysql数据库默认当连续8小时不对 ...

  5. TCP/IP网络编程之多播与广播

    多播 多播方式的数据传输是基于UDP完成的,因此,与UDP服务端/客户端的实现非常接近.区别在于,UDP数据传输以单一目标进行,而多播数据同时传递到加入(注册)特定组的大量主机.换言之,采用多播方式时 ...

  6. itchat 总结(转)

    python实现微信接口(itchat) 安装 sudo pip install itchat 登录 itchat.auto_login() 这种方法将会通过微信扫描二维码登录,但是这种登录的方式确实 ...

  7. flex布局之flex-grow和flex-shrink如何计算

    此文已由作者张含会授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 关于盒模型布局 如何实现两栏布局? (表格) 流式, 浮动, 定位 如何选择? 流式 > 浮动 > ...

  8. C#入门篇-3:数据类型及转换

    using System; using System.Text; using System.Collections; using System.Collections.Generic; //003 查 ...

  9. 最好用的远程连接工具TeamviWer13安装教程(Win10环境)

    1.Teamviwer官网:https://www.teamviewer.com/zhCN/ 2.下载链接:https://dl.tvcdn.de/download/TeamViewer_Setup. ...

  10. Java的移位运算符

    1.左移运算符:<< 丢弃左边指定位数,右边补0. 注意: 当int类型进行左移操作时,左移位数大于等于32位操作时,会先求余(%)后再进行左移操作.也就是说左移32位相当于不进行移位操作 ...