一、开发环境
数据库:SQLServer2008
编译器:VS2010
.Net版本:.Net Framework 4.0
二、涉及第三方程序集
NHibernate.dll:版本3.2
Iesi.Collections.dll
三、开发过程
1.项目结构
2.添加Product.cs
namespace NHLearn.Domain { public class Product { public int Id { get; set; } public String Name { get; set; } public decimal UnitPrice { get; set; } } }
3.添加Product.hbm.xml,属性为嵌入的资源
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false"> <class name="NHLearn.Domain.Product,NHLearn.Domain" table="T_Product"> <id name="Id" column="Id" type="int"> <generator class="native" /> </id> <property name="Name" column="Name" /> <property name="UnitPrice" column="UnitPrice" /> </class> </hibernate-mapping>
4.配置NHibernate
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler,NHibernate" requirePermission="false"/> </configSections> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" > <session-factory> <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider, NHibernate</property> <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property> <property name="connection.connection_string">Server=(local);initial catalog=NHLearn_DB;uid=sa;pwd=woaini</property> <property name="show_sql">true</property> <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property> </session-factory> </hibernate-configuration> </configuration>
5.增删改成
5.0控制台中代码
namespace NHLearn.UI { class Program { private static ISession session = null; private static ISessionFactory factory = null; private static ITransaction trans = null; static void Main(string[] args) { #region 1.0初始化session工厂 Configuration config = new Configuration().AddAssembly("NHLearn.Domain"); factory = config.BuildSessionFactory(); session = factory.OpenSession(); #endregion //Add(); //Query(); //Modify(); //Delete(); Console.ReadKey(); } } }
5.1添加方法
public static void Add() { Product model = new Product() { Name = "Apple", UnitPrice = 2.6m }; session.Save(model); }
5.2查询方法
public static void Query() { Product model = session.Get(typeof(Product), 1) as Product; Console.WriteLine(model.Name); }
5.3修复方法
public static void Modify() { Product model = session.Get(typeof(Product), 1) as Product; model.Name = "Orange"; session.Update(model); Console.WriteLine(model.Name); }
5.4删除方法
public static void Delete() { trans = session.BeginTransaction(); try { Product model = session.Get(typeof(Product), 1) as Product; session.Delete(model); trans.Commit(); Console.WriteLine("删除成功"); } catch (Exception ex) { trans.Rollback(); Console.WriteLine(ex.Message); } }
四、其他说明
增删改都是可以加事务的