Nhibernate基本的增删改查实践
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下载地址:
- http://sourceforge.net/projects/nhibernate/
- http://www.nuget.org/packages/NHibernate/
- http://hibernate.org/
NHibernate参考手册:NHibernate.chm.rar
Nhibernate基本的增删改查实践的更多相关文章
- 大数据系列之分布式数据库HBase-0.9.8安装及增删改查实践
若查看HBase-1.2.4版本内容及demo代码详见 大数据系列之分布式数据库HBase-1.2.4+Zookeeper 安装及增删改查实践 1. 环境准备: 1.需要在Hadoop启动正常情况下安 ...
- 大数据系列之分布式数据库HBase-1.2.4+Zookeeper 安装及增删改查实践
之前介绍过关于HBase 0.9.8版本的部署及使用,本篇介绍下最新版本HBase1.2.4的部署及使用,有部分区别,详见如下: 1. 环境准备: 1.需要在Hadoop[hadoop-2.7.3] ...
- Mybatis连接Oracle实现增删改查实践
1. 首先要在项目中增加Mybatis和Oracle的Jar文件 这里我使用的版本为ojdbc7 Mybatis版本为:3.2.4 2. 在Oracle中创建User表 create table T_ ...
- 一个使用MVC3+NHibernate “增删改查” 的项目
一个使用MVC3+NHibernate “增删改查” 的项目 前言: 谈到NHibernate大伙并不陌生,搞Java的更是清楚,Hibernate是一个目前应用的最广泛的开放源代码的对象关系映射框 ...
- MVC项目实践,在三层架构下实现SportsStore-11,使用Knockout实现增删改查
SportsStore是<精通ASP.NET MVC3框架(第三版)>中演示的MVC项目,在该项目中涵盖了MVC的众多方面,包括:使用DI容器.URL优化.导航.分页.购物车.订单.产品管 ...
- 【C#】使用NHibernate连接MySQL数据库及增删改查
学习资料 http://www.sikiedu.com/course/51/task/891/show https://www.codeproject.com/Articles/26123/NHibe ...
- NHibernate初学一之简单增删改查
以前有简单了解NHibernate,但因项目一直没有运用所以也没有机会进行一个详细了解:最近利用一点空闲的时间认真学习它:同样希望把学习过程进行简单记录,今天简单写一个针对MSSQL数据库的增删改查的 ...
- 一个使用MVC3+NHibernate “增删改查” 的项目(修正版)
前言: 谈到NHibernate大伙并不陌生,搞Java的更是清楚,Hibernate是一个目前应用的最广泛的开放源代码的对象关系映射框架,它对Java的JDBC(类似于ADO.Net)进行了非常 ...
- 使用NHibernate连接MySQL数据库及增删改查
学习资料 http://www.sikiedu.com/course/51/task/891/show https://www.codeproject.com/Articles/26123/NHibe ...
随机推荐
- 【原创】数据处理中判断空值的方法(np.isnan、is np.nan和pd.isna)比较
转载请注明出处:https://www.cnblogs.com/oceanicstar/p/10869725.html 1.np.isnan(只有数组数值运算时可使用) 注意:numpy模块的i ...
- PHP静态文件缓存
ob_start(); 2 echo 'aaa'; 3 $string = ob_get_contents(); 4 file_put_contents('a.html', $string); 5 o ...
- ECMAScript 6入门扩展笔记
字符串扩展 Unicode相关补充 引入"\u{xx}"来表示码点,之前只能表示\u0000-\uffff引入String.fromCodePoint()能正确读取大于uFFFF的 ...
- [译]The Python Tutorial#2. Using the Python Interpreter
[译]The Python Tutorial#Using the Python Interpreter 2.1 Invoking the Interpreter Python解释器通常安装在目标机器的 ...
- libevent 信号事件实现方式
学会使用libevent,才能真正的掌握其是实现原理,我们先从一个简短的测试用例开始: #include <sys/types.h> #include <sys/stat.h> ...
- astyle 使用说明 —— 集成到开发平台中
转自:https://www.cnblogs.com/jiangxinnju/p/4908575.html 欢迎关注我的社交账号: 博客园地址: http://www.cnblogs.com/jian ...
- Apache的安装与下载
PHP的运行必然少不了服务器的支持,何为服务器?通俗讲就是在一台计算机上,安装个服务器软件,这台计算机便可以称之为服务器,服务器软件和计算机本身的操作系统是两码事,计算机自身的操作系统可以为linux ...
- tomcat缓存
问题描述: 一个用到struts2框架的web项目,由于在struts.xml中少配置了一个action,导致项目运行时报异常.将原本好的代码复旧,重启tomcat服务,第一次加载程序没问题,再刷新时 ...
- leetcode 【 Reorder List 】python 实现
题目: Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You must do ...
- Android onConfigurationChanged用法(规避横竖屏切换导致的重新调用onCreate方法)
onConfigurationChanged的目的是为了规避横竖屏切换干掉activity而重新调用onCreate方法的问题:有的时候,我们希望重新进入OnCreate生命周期,此时可以调用onSa ...