NHibernate系列文章十二:Load/Get方法

摘要

NHibernate提供两个方法按主键值查找对象:Load/Get。

1. Load/Get方法的区别

Load:

  • Load方法可以对查询进行优化。
  • Load方法实际得到一proxy对象,并不立即查询数据库。当访问对象的属性的时候才查询数据库。在NHibernate里称为Lazy Loding(延迟加载)。
  • Load方法得到的对象,如果对象不存在,在访问对象的属性时将抛出异常。
  • 当需要得到实体对象,但是不需要访问对象属性的时候,宜使用Load方法。比如Delete方法:
1         private static void Delete(int id)
2         {
3             using (var session = SessionFactory.OpenSession())
4             {
5                 var customer = session.Load<Customer>(id);
6                 session.Delete(customer);
7                 session.Flush();
8             }
9         }

Get:

  • Get方法立即查询数据库,如果对象不存在,返回null。

2. 程序演示

修改SessionFactory属性,添加cfg.DataBaseIntegration,让控制台输出执行的SQL语句。

 1         public static ISessionFactory SessionFactory
 2         {
 3             get
 4             {
 5                 if (_sessionFactory == null)
 6                 {
 7                     var cfg = new Configuration();
 8                     cfg.DataBaseIntegration(x=> {
 9                         x.LogSqlInConsole = true;
10                     });
11                     cfg.Configure();
12                     _sessionFactory = cfg.BuildSessionFactory();
13                 }
14                 return _sessionFactory;
15             }
16         }

修改Main函数

 1         static void Main(string[] args)
 2         {
 3             HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
 4 
 5             using (var session = SessionFactory.OpenSession())
 6             {
 7                 var customerExist = session.Get<Customer>(1);
 8                 var customerNotExist = session.Get<Customer>(5);
 9                 Console.WriteLine("customer id = 1");
10                 Console.WriteLine(customerExist != null ? "existed" : "not existed");
11                 Console.WriteLine("customer id = 5");
12                 Console.WriteLine(customerNotExist != null ? "existed" : "not existed");
13             }
14 
15             using (var session = SessionFactory.OpenSession())
16             {
17                 var customerExist = session.Load<Customer>(1);
18                 Console.WriteLine("load customer id = 1");
19                 string lastName = customerExist.LastName;
20                 try
21                 {
22                     var customerNotExist = session.Load<Customer>(5);
23                     lastName = customerNotExist.LastName;
24                 }
25                 catch (HibernateException e)
26                 {
27                     throw e;
28                 }
29             }
30 
31             Console.WriteLine("Completed");
32             Console.ReadLine();
33         }

执行程序,得到结果

load customer id = 1的输出是在查询语句前输出的,说明了Load方法在访问查询结果对象的属性时才去访问数据库。

Load不存在的对象,访问对象属性时抛出异常。

原文地址:https://www.cnblogs.com/uncle_danny/p/5638858.html