摘要
上一篇文章只完成了简单的NHibernate安装、配置和连接数据库。这篇文章介绍怎样实现最简单的数据库读写操作。
1. 重构ISessionFactory生成过程
将生成ISessionFactory的代码从main函数中移除,变成使用属性控制。
1 private static ISessionFactory _sessionFactory; 2 3 public static ISessionFactory SessionFactory 4 { 5 get 6 { 7 if (_sessionFactory == null) 8 { 9 var cfg = new Configuration(); 10 11 cfg.DataBaseIntegration(x => 12 { 13 x.ConnectionString = "Data Source=localhost;Initial Catalog=NHibernateDemoDB;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; 14 x.Driver<SqlClientDriver>(); 15 x.Dialect<MsSql2008Dialect>(); 16 }); 17 cfg.AddAssembly(Assembly.GetExecutingAssembly()); 18 _sessionFactory = cfg.BuildSessionFactory(); 19 } 20 return _sessionFactory; 21 } 22 }
SessionFactory的创建很占用系统资源,一般在整个应用程序中只创建一次。因此,这里通过判断if (_sessionFactory == null)实现一个最简单的单例模式。
2. GetAll和GetById函数代码
1 private static IList<Customer> GetAll() 2 { 3 using (var session = SessionFactory.OpenSession()) 4 { 5 IList<Customer> list = session.CreateCriteria<Customer>().List<Customer>(); 6 return list; 7 } 8 } 9 10 private static Customer GetById(int id) 11 { 12 using (var session = SessionFactory.OpenSession()) 13 { 14 Customer customer = session.Get<Customer>(id); 15 return customer; 16 } 17 }
使用using子句,在using代码块完成后,将自动调用ISession的Dispose方法关闭Session
3. 增删改函数代码
1 private static int Insert(Customer customer) 2 { 3 using (var session = SessionFactory.OpenSession()) 4 { 5 var identifier = session.Save(customer); 6 session.Flush(); 7 return Convert.ToInt32(identifier); 8 } 9 } 10 11 private static void Update(Customer customer) 12 { 13 using (var session = SessionFactory.OpenSession()) 14 { 15 session.SaveOrUpdate(customer); 16 session.Flush(); 17 } 18 } 19 20 private static void Delete(int id) 21 { 22 using (var session = SessionFactory.OpenSession()) 23 { 24 var customer = session.Load<Customer>(id); 25 session.Delete(customer); 26 session.Flush(); 27 } 28 }
- session.Save: 插入新记录,返回新纪录主键值
- session.SaveOrUpdate: 如果被调用的Customer对象在数据库里不存在(新记录),则插入新记录,否则修改该记录
- session.Delete: 传入Customer对象进行删除
- 增删改操作完成之后需要调用session.Flush()方法,将对象持久化写入数据库。如果不调用此方法,方法结束后修改记录不能写入到数据库
4. 添加方法CreateCustomer
1 private static Customer CreateCustomer() 2 { 3 var customer = new Customer 4 { 5 FirstName = "Daniel", 6 LastName = "Tang", 7 Points = 100, 8 HasGoldStatus = true, 9 MemberSince = new DateTime(2012, 1, 1), 10 CreditRating = CustomerCreditRating.Good, 11 AverageRating = 42.42424242, 12 Street = "123 Somewhere Avenue", 13 City = "Nowhere", 14 Province = "Alberta", 15 Country = "Canada" 16 }; 17 18 return customer; 19 }
5. 修改main函数
1 static void Main(string[] args) 2 { 3 Customer newCustomer = CreateCustomer(); 4 int customerId = Insert(newCustomer); 5 Console.WriteLine("new customer id: {0}", customerId); 6 7 IList<Customer> list = GetAll(); 8 Console.WriteLine("customer list count: {0}", list.Count); 9 foreach(var item in list) 10 { 11 Console.WriteLine("{0} {1}", item.FirstName, item.LastName); 12 } 13 14 var customer = GetById(customerId); 15 Console.WriteLine("GetById: {0} {1}", customer.FirstName, customer.LastName); 16 17 customer.LastName = "Chen"; 18 Update(customer); 19 var updatedCustomer = GetById(customerId); 20 Console.WriteLine("updated: {0} {1}", updatedCustomer.FirstName, updatedCustomer.LastName); 21 22 Delete(customerId); 23 var existedCustomer = GetById(customerId); 24 Console.WriteLine("after deleted: existing: {0}", existedCustomer != null); 25 26 Console.ReadLine(); 27 }
6. 完整的代码
1 using NHibernate; 2 using NHibernate.Cfg; 3 using NHibernate.Dialect; 4 using NHibernate.Driver; 5 using System; 6 using System.Collections.Generic; 7 using System.Reflection; 8 9 namespace NHibernateDemoApp 10 { 11 class Program 12 { 13 private static ISessionFactory _sessionFactory; 14 15 public static ISessionFactory SessionFactory 16 { 17 get 18 { 19 if (_sessionFactory == null) 20 { 21 var cfg = new Configuration(); 22 23 cfg.DataBaseIntegration(x => 24 { 25 x.ConnectionString = "Data Source=localhost;Initial Catalog=NHibernateDemoDB;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; 26 x.Driver<SqlClientDriver>(); 27 x.Dialect<MsSql2008Dialect>(); 28 }); 29 cfg.AddAssembly(Assembly.GetExecutingAssembly()); 30 _sessionFactory = cfg.BuildSessionFactory(); 31 } 32 return _sessionFactory; 33 } 34 } 35 36 static void Main(string[] args) 37 { 38 Customer newCustomer = CreateCustomer(); 39 int customerId = Insert(newCustomer); 40 Console.WriteLine("new customer id: {0}", customerId); 41 42 IList<Customer> list = GetAll(); 43 Console.WriteLine("customer list count: {0}", list.Count); 44 foreach(var item in list) 45 { 46 Console.WriteLine("{0} {1}", item.FirstName, item.LastName); 47 } 48 49 var customer = GetById(customerId); 50 Console.WriteLine("GetById: {0} {1}", customer.FirstName, customer.LastName); 51 52 customer.LastName = "Chen"; 53 Update(customer); 54 var updatedCustomer = GetById(customerId); 55 Console.WriteLine("updated: {0} {1}", updatedCustomer.FirstName, updatedCustomer.LastName); 56 57 Delete(customerId); 58 var existedCustomer = GetById(customerId); 59 Console.WriteLine("after deleted: existing: {0}", existedCustomer != null); 60 61 Console.ReadLine(); 62 } 63 64 private static Customer CreateCustomer() 65 { 66 var customer = new Customer 67 { 68 FirstName = "Daniel", 69 LastName = "Tang", 70 Points = 100, 71 HasGoldStatus = true, 72 MemberSince = new DateTime(2012, 1, 1), 73 CreditRating = CustomerCreditRating.Good, 74 AverageRating = 42.42424242, 75 Street = "123 Somewhere Avenue", 76 City = "Nowhere", 77 Province = "Alberta", 78 Country = "Canada" 79 }; 80 81 return customer; 82 } 83 84 private static IList<Customer> GetAll() 85 { 86 using (var session = SessionFactory.OpenSession()) 87 { 88 IList<Customer> list = session.CreateCriteria<Customer>().List<Customer>(); 89 return list; 90 } 91 } 92 93 private static Customer GetById(int id) 94 { 95 using (var session = SessionFactory.OpenSession()) 96 { 97 Customer customer = session.Get<Customer>(id); 98 return customer; 99 } 100 } 101 102 private static int Insert(Customer customer) 103 { 104 using (var session = SessionFactory.OpenSession()) 105 { 106 var identifier = session.Save(customer); 107 session.Flush(); 108 return Convert.ToInt32(identifier); 109 } 110 } 111 112 private static void Update(Customer customer) 113 { 114 using (var session = SessionFactory.OpenSession()) 115 { 116 session.SaveOrUpdate(customer); 117 session.Flush(); 118 } 119 } 120 121 private static void Delete(int id) 122 { 123 using (var session = SessionFactory.OpenSession()) 124 { 125 var customer = session.Load<Customer>(id); 126 session.Delete(customer); 127 session.Flush(); 128 } 129 } 130 } 131 }
7. 执行结果
作者:丹尼大叔
出处:http://www.cnblogs.com/uncle_danny
本文版权归作者和博客园共有,欢迎转载。但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。