在李永京NHibernate之旅(5)中,关于更新对象中的一个测试是这样的:
[Test]
public void UpdateCustomerTest()
{
var customer = _crud.GetCustomerById(1);
customer.Firstname = "liyongjing";
_crud.UpdateCustomer(customer);
var testCustomer = _crud.GetCustomerById(1);
Assert.AreEqual("liyongjing", customer.Firstname);
}
我跟踪了一下SQL语句的执行,发现这个测试执行的过程中,如果对象发生了变化,则只有两条SQL语句:
exec sp_executesql N'SELECT customer0_.CustomerId as CustomerId0_0_, customer0_.Version as Version0_0_,
customer0_.Firstname as Firstname0_0_, customer0_.Lastname as Lastname0_0_ FROM Customer customer0_
WHERE customer0_.CustomerId=@p0',N'@p0 int',@p0=3
exec sp_executesql N'UPDATE Customer SET Version = @p0, Firstname = @p1, Lastname = @p2 WHERE CustomerId =
@p3 AND Version = @p4',N'@p0 int,@p1 nvarchar(50),@p2 nvarchar(50),@p3 int,@p4 int',@p0=7,@p1=N'zzzz',
@p2=N'YQ',@p3=3,@p4=6
如果没有做任何更新,则只有一条SQL语句:
exec sp_executesql N'SELECT customer0_.CustomerId as CustomerId2_0_, customer0_.Version as Version2_0_,
customer0_.Firstname as Firstname2_0_, customer0_.Lastname as Lastname2_0_ FROM Customer customer0_ WHERE
customer0_.CustomerId=@p0',N'@p0 int',@p0=3
var testCustomer = _crud.GetCustomerById(1);
NHibernate一级缓存介绍
NHibernate一级缓存即ISession缓存,ISession缓存属于事务级缓存,是NHibernate内置的。ISession缓存中的数据只在本ISession周期内使用。
ISession实例创建后即可使用ISession缓存。此后,ISession实例操作数据时,首先查询内置缓存,如果ISession缓存中存在相应数据,则直接使用缓存数据。如果不存在,则查询数据库并把其结果存在缓存中。
实例1:查询一次持久化实例
[Test]
public void SessionCacheTest()
{
Customer customer = _transaction.GetCustomerById(1);
}
我们一般就是这样查询一条数据,NHibernate初始化ISession后,ISession缓存中不存在这个数据,这时NHibernate需要从数据库中加载数据。
原来是缓存啊