C#的NHibernate的CRUD开发入门代码例子
程序员文章站
2022-07-14 11:26:03
...
本文档适合初级开发者或者是第一次接触NHibernate框架的朋友,其中NHibernate不是最新的版本,
但是一个比较经典的版本 NHibernate 2.1.2,其中用红线标注的部分一定要仔细看,
这些都是容易忽略和出错的地方,笔者在此给大家做了特殊标记。
NHibernate框架的介绍:http://baike.baidu.com/view/954535.htm
开发环境 Vs 2010 + MsSql2005 + NHibernate 2.1.2.
本示例的下载地址:点击下载;NHibernate 2.1.2的下载地址:点击下载;
官方:http://sourceforge.net/projects/nhibernate/
学习网:http://nmg.codeplex.com/
目录
步骤一、创建数据库和映射的表。
步骤二、创建项目和实体类映射类以及类对应的映射文件。
步骤三、添加项目引用与NHibernate的dll文件。
步骤四、配置hibernate.cfg.xml文件(数据库映射信息配置)无需配置web.config。
步骤五、创建和使用NHibernate.
/***
* 此代码工程是三年前写的例子.
*@Author:liangjilong
*@Date:2012/08/xx
*@Email:jilongliang@sina.aom
*/
NHibernate跟hibernate没几乎没区别,一个是java语言开发出来的,一个是c#开发的出来
的类库包,当你用c#反编译出来你就看到很多.cs的文件,在此也不用多介绍,最好的就是贴例子
和项目出来。
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Model" namespace="Model"> <class name ="Model.Entities.Users,Model" table="Users"> <id name="Id" column="Id" type="Int32" unsaved-value="0"> <generator class ="native"></generator> </id> <property name="UserName" column ="UserName" type="string" length="20" not-null="false"/> <property name="PassWord" column="PassWord" type="string" length="100" not-null="false"/> <property name="Address" column="Address" tpye="string" length="100" not-null="false"/> </class> </hibernate-mapping>
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Model { //在c#的实体类跟java的实体类有区别,区别是在于set和get //java的是getXX/setXX,c#不需要.它是简化了,毕竟才c#是为了自己有一套不能完全抄袭 //java的,只能抄袭java的思想 public class Users { private int Id { set; get; } private string UserName { set;get; } private string PassWord { set; get; } private string Address { set; get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using NHibernate.Cfg; using NHibernate; using Model; namespace DAL { public class UsersDAL { /// <summary> /// HttpContext是System.Web里面的类 /// 封装有关个别 HTTP 请求的所有 HTTP 特定的信息。 /// </summary> private string path = HttpContext.Current.Server.MapPath("~/hibernate.cfg.xml"); /// <summary> /// 插入 /// </summary> /// <param name="userInfo"></param> /// <returns></returns> public bool Insert(Users users) { //读取Nhibernate的配置Configuration Configuration cfg = new Configuration().Configure(path); //创建Session ISession session = cfg.BuildSessionFactory().OpenSession(); ITransaction transaction = session.BeginTransaction(); try { //保存用户 session.Save(users); transaction.Commit(); return true; } catch (Exception e) { transaction.Rollback(); return false; } finally { session.Close(); } } /// <summary> /// 查询所有用户信息 /// </summary> /// <returns></returns> public IList<Users> GetUsers() { Configuration cfg = new Configuration().Configure(path); ISession session = cfg.BuildSessionFactory().OpenSession(); //使用NHQL IList<Users> list = session.CreateQuery(" from Users").List<Users>(); return list; } /// <summary> /// 更新用户 /// </summary> /// <param name="users"></param> /// <returns></returns> public bool Update(Users users) { //读取Nhibernate的配置Configuration Configuration cfg = new Configuration().Configure(path); //打开Nhibernate的Session ISession session = cfg.BuildSessionFactory().OpenSession(); ITransaction transaction = session.BeginTransaction(); try { session.Update(users); transaction.Commit();//提交事务 return true; } catch (Exception e) { //回滚事务 transaction.Rollback(); return false; } finally { //关闭事务 session.Close(); } } /// <summary> /// 删除用户 /// </summary> /// <param name="users"></param> /// <returns></returns> public bool Delete(Users users) { ////读取Nhibernate的配置Configuration Configuration cfg = new Configuration().Configure(path); //打开Nhibernate的Session ISession session = cfg.BuildSessionFactory().OpenSession(); ITransaction transaction = session.BeginTransaction(); try { //删除用户 session.Delete(users); transaction.Commit();//提交事务 return true; } catch (Exception e) { //回滚事务 transaction.Rollback(); return false; } finally { session.Close();//关闭事务 } } /// <summary> /// 根据用户ID去查询 /// </summary> /// <param name="userId"></param> /// <returns></returns> public Users GetUserById(int userId) { Configuration cfg = new Configuration().Configure(path); ISession session = cfg.BuildSessionFactory().OpenSession(); return session.Get<Users>(userId); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Model; using DAL; namespace BLL { public class UsersBLL { /// <summary> /// 插入信息 /// </summary> /// <param name="users"></param> /// <returns></returns> public bool Insert(Users users) { return new UsersDAL().Insert(users); } /// <summary> /// 获取所有用户信息 /// </summary> /// <returns></returns> public IList<Users> GetUsers() { return new UsersDAL().GetUsers(); } /// <summary> /// 更新用户 /// </summary> /// <param name="users"></param> /// <returns></returns> public bool Update(Users users) { return new UsersDAL().Update(users); } /// <summary> /// 删除用户 /// </summary> /// <param name="users"></param> /// <returns></returns> public bool Delete(Users users) { return new UsersDAL().Delete(users); } /// <summary> /// 通过ID去查询 /// </summary> /// <param name="userId"></param> /// <returns></returns> public Users GetUserById(int userId) { return new UsersDAL().GetUserById(userId); } } }
<?xml version="1.0" encoding="utf-8"?> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" > <session-factory name="NHibernate"> <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property> <property name="connection.connection_string"> Data Source=.;Initial Catalog=CRMEasy;Persist Security Info=True;User ID=sa;Password=admin1988 </property> <property name="adonet.batch_size">10</property> <property name="show_sql">false</property> <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property> <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="Model"/> </session-factory> </hibernate-configuration>
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using BLL; using System.Collections.Generic; using Model; namespace WebApp { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { UsersBLL u = new UsersBLL(); IList<Users> list = u.GetUsers(); GridView1.DataSource = list; GridView1.DataBind(); } } }
代码在百度网盘链接: http://pan.baidu.com/s/1c1neoz2 密码: dff8