01-08-05【Nhibernate (版本3.3.1.4000) 出入江湖】NHibernate二级缓存:第三方MemCache缓存

一、准备工作

【1】根据操作系统(位数)选择下载相应版本的MemCache,

MemCache的下载和安装,参看:

http://www.cnblogs.com/easy5weikai/p/3760677.html

【2】第三方MemCache缓存适配器,下载地址:

http://sourceforge.net/projects/nhcontrib/files/NHibernate.Caches/

根据版本号自行下载。

特别说明:

1.一定要版本一致

  MemCache缓存适配器写本文的时候最高版本是:NHCH-3.2.0.GA-bin(不支持目前高版本的NhibernateNhibernate (版本3.3.1.4000))

下载地址:http://sourceforge.net/projects/nhcontrib/files/NHibernate.Caches/

  1-1 它依赖的Nhibernate的版本是NHibernate-3.2.0.GA-bin,下载地址:

http://sourceforge.net/projects/nhibernate/files/NHibernate/

  1-2 它依赖的Log4net的版本是log4net-1.2.10

2.MemCache缓存依赖Log4net的版本是log4net-1.2.10

  只要添加对log4net程序集的引用即可,不一定要在app/web.config文件中配置<log4net>节点。

-------------------

其他资料 :

http://sourceforge.net/projects/nhcontrib/files/

二、开始动手搭建NHibernate二级缓存:第三方MemCache缓存

----------------------------------------------------------------------------------------

第一步:在应用程序配置文件(app.config or web.config)中添加

  <configSections>
<section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System,
Version=3.2.0.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4" />
<section name ="memcache" type ="NHibernate.Caches.MemCache.MemCacheSectionHandler,NHibernate.Caches.MemCache" />
</configSections> <memcache>
<memcached host ="127.0.0.1" port ="" weight ="" />
</memcache >

第二步:DomainModel层的实体映射配置文件(如:Cusomer.hbm.xml)的配置

和前面的配置一模一样,请查看:

http://www.cnblogs.com/easy5weikai/p/3759277.html

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="Model"
assembly="Model"
default-lazy="true"> <class name="Model.Customer, Model"
table="Customer"
discriminator-value="" lazy="true">
<!--.这个不是必须的,因为在nhibernate.cfg.xml文件中已经有了一个总配置
.cache标签必须在id标签前面
-->
<cache usage="read-write"/>
<!--unsaved-value="" 主键表中不需要定义,而是需要在子表中定义-->
<id name="CustomerId"
column="CustomerId"
type="int"
unsaved-value="">
<generator class="native" />
<!-- unsaved-value used to be null and generator was increment in h2.0.3 -->
</id>
。。。。。。
<set name="Orders" table="Order" lazy="false"
generic="true"
inverse="false" cascade="all">
<!--二级缓存策略-->
<cache usage="read-write"/>
<key column="CustomerId" foreign-key="FK_CustomerOrders"/>
<one-to-many class="Model.Order,Model"/>
</set>
</class>
</hibernate-mapping>

第三步:添加如下程序集的引用:

1.NHibernate.Caches.MemCache.dll,

2.Memcached.ClientLibrary.dll,

3.ICSharpCode.SharpZipLib.dll

4.log4net.dll

第四步:在hibernate.cfg.xml文件中添加:

    <!--=======加入Nhibernate第三方二级缓存的memcache的配置===开始=============================-->
<property name ="cache.provider_class" >NHibernate.Caches.MemCache.MemCacheProvider,NHibernate.Caches.MemCache</property >
<property name ="cache.use_second_level_cache" >true</property>
<property name ="cache.use_query_cache" >true</property>
<property name ="cache.default_expiration" ></property>
<property name ="cache.region_prefix" >Demo</property>
<!--=======加入Nhibernate第三方二级缓存的memcache的配置===结束=============================--> <!--实体类所在的程序集-->
<mapping assembly="Model"/>
<!--.配置映射的二级缓存-->
<class-cache class="Model.Customer,Model" usage="read-write"/>
<!--<collection-cache collection ="集合名称" region="默认集合名称"
usage="read-write"/>-->

第五步:应用程序配置文件(app.config or web.config)中添加log4net的节点配置(可选,可不用配置):

  <configSections>
<section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System,
Version=3.2.0.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
<section name ="memcache" type ="NHibernate.Caches.MemCache.MemCacheSectionHandler,NHibernate.Caches.MemCache" />
</configSections <log4net>
<!--定义输出到文件中-->
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender,log4net">
<!--<appender name="LogFileAppender" type="log4net.Appender.FileAppender">-->
<!--定义文件存放位置-->
<file value="log4netfile.log" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd-HH:mm:ss" />
<layout type="log4net.Layout.PatternLayout">
<!--输出格式-->
<!--样例:-- ::, [] INFO Log4NetDemo.MainClass [(null)] - info-->
<conversionPattern value="记录时间:%date 线程ID:[%thread] 日志级别:%-5level 出错类:%logger property:[%property{NDC}] - 错误描述:%message%newline" />
</layout>
</appender>
<!--定义输出到控制台命令行中-->
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<!--定义输出到windows事件中-->
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<!--定义输出到数据库中,这里举例输出到Access数据库中,数据库为C盘的log4net.mdb-->
<appender name="AdoNetAppender_Access" type="log4net.Appender.AdoNetAppender">
<connectionString value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:log4net.mdb" />
<commandText value="INSERT INTO LogDetails ([LogDate],[Thread],[Level],[Logger],[Message]) VALUES (@logDate, @thread, @logLevel, @logger,@message)" />
<!--定义各个参数-->
<parameter>
<parameterName value="@logDate" />
<dbType value="String" />
<size value="" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date" />
</layout>
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="@logLevel" />
<dbType value="String" />
<size value="" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
</appender>
<!--定义日志的输出媒介,下面定义日志以四种方式输出。也可以下面的按照一种类型或其他类型输出。-->
<root>
<!--文件形式记录日志-->
<appender-ref ref="LogFileAppender" />
<!--控制台控制显示日志-->
<appender-ref ref="ConsoleAppender" />
<!--Windows事件日志-->
<appender-ref ref="EventLogAppender" />
<!-- 如果不启用相应的日志记录,可以通过这种方式注释掉
<appender-ref ref="AdoNetAppender_Access" />
-->
</root>
</log4net>

大功搞成。当然要确保Mecache服务已经安装并开启了。

最后看下各个文件的最终的配置:

app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System,
Version=3.2.0.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
<section name ="memcache" type ="NHibernate.Caches.MemCache.MemCacheSectionHandler,NHibernate.Caches.MemCache" />
</configSections>
<log4net>
<!--定义输出到文件中-->
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender,log4net">
<!--<appender name="LogFileAppender" type="log4net.Appender.FileAppender">-->
<!--定义文件存放位置-->
<file value="log4netfile.log" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd-HH:mm:ss" />
<layout type="log4net.Layout.PatternLayout">
<!--输出格式-->
<!--样例:-- ::, [] INFO Log4NetDemo.MainClass [(null)] - info-->
<conversionPattern value="记录时间:%date 线程ID:[%thread] 日志级别:%-5level 出错类:%logger property:[%property{NDC}] - 错误描述:%message%newline" />
</layout>
</appender>
<!--定义输出到控制台命令行中-->
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<!--定义输出到windows事件中-->
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<!--定义输出到数据库中,这里举例输出到Access数据库中,数据库为C盘的log4net.mdb-->
<appender name="AdoNetAppender_Access" type="log4net.Appender.AdoNetAppender">
<connectionString value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:log4net.mdb" />
<commandText value="INSERT INTO LogDetails ([LogDate],[Thread],[Level],[Logger],[Message]) VALUES (@logDate, @thread, @logLevel, @logger,@message)" />
<!--定义各个参数-->
<parameter>
<parameterName value="@logDate" />
<dbType value="String" />
<size value="" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date" />
</layout>
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="@logLevel" />
<dbType value="String" />
<size value="" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
</appender>
<!--定义日志的输出媒介,下面定义日志以四种方式输出。也可以下面的按照一种类型或其他类型输出。-->
<root>
<!--文件形式记录日志-->
<appender-ref ref="LogFileAppender" />
<!--控制台控制显示日志-->
<appender-ref ref="ConsoleAppender" />
<!--Windows事件日志-->
<appender-ref ref="EventLogAppender" />
<!-- 如果不启用相应的日志记录,可以通过这种方式注释掉
<appender-ref ref="AdoNetAppender_Access" />
-->
</root>
</log4net> <memcache>
<memcached host ="127.0.0.1" port ="" weight ="" />
</memcache >
</configuration>

hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!--
This template was written to work with NHibernate.Test.
Copy the template to your NHibernate.Test project folder and rename it in hibernate.cfg.xml and change it
for your own use before compile tests in VisualStudio.
-->
<!-- This is the System.Data.dll provider for SQL Server -->
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="NHibernate.Test123456">
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string"> <!--用于测试自动生成数据库表(不自动生成数据库)-->
<!--<property name="hbm2ddl.auto">update</property>-->
Server=(local);initial catalog=NHibernateSampleAutoCreateTable;Integrated Security=SSPI <!--Server=(local);initial catalog=NHibernateSample;Integrated Security=SSPI-->
</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property> <!--输出所有的SQL语句到控制台,一般开发打开这个-->
<property name="show_sql">true</property>
<!--整齐的SQL输出到控制台-->
<property name="format_sql">true</property>
<!--自动生成数据库表(不自动生成数据库)-->
<property name="hbm2ddl.auto">update</property>
<!--在数据表设计中如果采用了 bit 类型的字段,并且对应了业务类中类型为 bool 值,一定要如上设置下-->
<property name="query.substitutions">true , false , yes 'Y', no 'N'</property> <!--=======加入Nhibernate自身的HashtabeCache的二级缓存配置==开始===========================-->
<!--.配置二级缓存提供程序-->
<!-- <property name="cache.provider_class">NHibernate.Cache.HashtableCacheProvider</property>-->
<!--.显式启用二级缓存-->
<!--<property name ="cache.use_second_level_cache">true</property>-->
<!--.启动查询缓存-->
<!--<property name="cache.use_query_cache">true</property>--> <!--=======加入Nhibernate自身的HashtabeCache的二级缓存配置==结束===========================--> <!--=======加入Nhibernate第三方二级缓存的memcache的配置===开始=============================-->
<property name ="cache.provider_class" >NHibernate.Caches.MemCache.MemCacheProvider,NHibernate.Caches.MemCache</property >
<property name ="cache.use_second_level_cache" >true</property>
<property name ="cache.use_query_cache" >true</property>
<property name ="cache.default_expiration" ></property>
<property name ="cache.region_prefix" >Demo</property>
<!--=======加入Nhibernate第三方二级缓存的memcache的配置===结束=============================--> <!--实体类所在的程序集-->
<mapping assembly="Model"/>
<!--.配置映射的二级缓存-->
<class-cache class="Model.Customer,Model" usage="read-write"/>
<!--<collection-cache collection ="集合名称" region="默认集合名称"
usage="read-write"/>--> </session-factory>
</hibernate-configuration>

Customer.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="Model"
assembly="Model"
default-lazy="true"> <class name="Model.Customer, Model"
table="Customer"
discriminator-value="" lazy="true">
<!--.这个不是必须的,因为在nhibernate.cfg.xml文件中已经有了一个总配置
.cache标签必须在id标签前面
-->
<cache usage="read-write"/>
<!--unsaved-value="" 主键表中不需要定义,而是需要在子表中定义-->
<id name="CustomerId"
column="CustomerId"
type="int"
unsaved-value="">
<generator class="native" />
<!-- unsaved-value used to be null and generator was increment in h2.0.3 -->
</id> <!--version标签必须放在Id后面,否则出错-->
<version name="Version"/> <property name="FirstName" not-null="true">
<column name="Firstname" length="" not-null="true"/>
</property> <property name="LastName" type="String">
<column name="Lastname"/>
</property> <property name="Age" type="int">
<column name="Age"/>
</property> <!--双向关联时要用:
inverse:由子表来维护关系,cascade:级联的关系 如果没有这个设置,
插入Customer成功(即使现在Order插入Order抛异常,这时产生了垃圾数据,
好的做法是用事务两者都能插入,避免垃圾数据的产生-->
<!--经测试:只需要在主表配置cascade="all",而子表不用配置cascade="all",
当删除主表实体时,子表的级联实体也会被删除-->
<!--cascade有几种??是吗??,分别表示级联操作的4种操作:
cascade = "none": 不能执行操作(有子时不给删父),经测试,为none时,添加父时没有自动添加子
cascade = "delete" : .级联(删父时删子),经测试,为delete时,添加父时自动添加子,
.经测试,当设置cascade = "all",MS SQL Server设置删除和更新操作虽然设置为:不执行操作,却被覆盖为联级
cascade = "null": (删父时子设置为null),但经测试Nhibernate不支持这个值
cascade = "???": 删父时子设置为默认值
cascade = "save-update":
cascade = "delete":
cascade = "all":
cascade = "all-delete-orphan":
-->
<set name="Orders" table="Order" lazy="false"
generic="true"
inverse="false" cascade="all">
<!--二级缓存策略-->
<cache usage="read-write"/>
<key column="CustomerId" foreign-key="FK_CustomerOrders"/>
<one-to-many class="Model.Order,Model"/>
</set>
</class>
</hibernate-mapping>

------------------------------------------------------------

测试一:

        [TestMethod]
public void TestSessionFactoryCacheGetCustomerHavingNotOrders()
{
CustomerService customerService = new CustomerService(); Customer customer = new Customer()
{
FirstName = "Test",
LastName = "TestSessionFactoryCache",
Age =
};
customerService.Add(customer);
int customerId = customer.CustomerId; Console.WriteLine("第1次获取数据------------------------------:");
Customer customerGet1 = customerService.Get(customerId);
Console.WriteLine("Id:{0}-->FirtstName:{1}"
, customerGet1.CustomerId, customerGet1.FirstName); Console.WriteLine("第2次获取数据==============================:");
Customer customerGet2 = customerService.Get(customerId);
Console.WriteLine("Id:{0}-->FirtstName:{1}"
, customerGet2.CustomerId, customerGet2.FirstName); Console.WriteLine("第3次获取数据==============================:");
Customer customerGet3 = customerService.Get(customerId);
Console.WriteLine("Id:{0}-->FirtstName:{1}"
, customerGet3.CustomerId, customerGet3.FirstName); }

测试结果:

NHibernate:
INSERT
INTO
Customer
(Version, Firstname, Lastname, Age)
VALUES
(@p0, @p1, @p2, @p3);
select
SCOPE_IDENTITY();
@p0 = [Type: Int32 ()],
@p1 = 'Test' [Type: String ()],
@p2 = 'TestSessionFactoryCache' [Type: String ()],
@p3 = [Type: Int32 ()]
第1次获取数据------------------------------:
NHibernate:
SELECT
customer0_.CustomerId as CustomerId0_0_,
customer0_.Version as Version0_0_,
customer0_.Firstname as Firstname0_0_,
customer0_.Lastname as Lastname0_0_,
customer0_.Age as Age0_0_
FROM
Customer customer0_
WHERE
customer0_.CustomerId=@p0;
@p0 = [Type: Int32 ()]
NHibernate:
SELECT
orders0_.CustomerId as CustomerId1_,
orders0_.OrderId as OrderId1_,
orders0_.OrderId as OrderId1_0_,
orders0_.Version as Version1_0_,
orders0_.OrderDate as OrderDate1_0_,
orders0_.CustomerId as CustomerId1_0_
FROM
[
Order] orders0_ WHERE
orders0_.CustomerId=@p0;
@p0 = [Type: Int32 ()]
Id:-->FirtstName:Test
第2次获取数据==============================:
Id:-->FirtstName:Test
第3次获取数据==============================:
Id:-->FirtstName:Test
第2次获取数据==============================:
Id:-->FirtstName:Test
第3次获取数据==============================:
Id:-->FirtstName:Test

说明,MemCache缓存起作用了。

测试二:

[TestMethod]
public void TestSessionFactoryCacheGetCustomerHavingOrders()
{
CustomerService customerService = new CustomerService();
Customer customer = new Customer()
{
FirstName = "Test",
LastName = "TestSessionFactoryCache",
Age =
};
Order order1 = new Order()
{
OrderDate = DateTime.Now,
Customer = customer
};
customer.Orders.Add(order1);
customerService.Add(customer); Console.WriteLine("第1次获取数据------------------------------:");
Customer customerGet1 = customerService.Get(customer.CustomerId);
Console.WriteLine("Id:{0}-->FirtstName:{1}"
,customerGet1.CustomerId,customerGet1.FirstName); Console.WriteLine("第2次获取数据==============================:");
Customer customerGet2 = customerService.Get(customer.CustomerId);
Console.WriteLine("Id:{0}-->FirtstName:{1}"
, customerGet2.CustomerId, customerGet2.FirstName); Console.WriteLine("第3次获取数据==============================:");
Customer customerGet3 = customerService.Get(customer.CustomerId);
Console.WriteLine("Id:{0}-->FirtstName:{1}"
, customerGet3.CustomerId, customerGet3.FirstName); }

【1】前置条件:如果Customer数据库中有Orders并且Orders的lazy="false"

    <set name="Orders" table="Order"  lazy="false"
generic="true"
inverse="false" cascade="all">
<!--二级缓存策略-->
<cache usage="read-write"/>
<key column="CustomerId" foreign-key="FK_CustomerOrders"/>
<one-to-many class="Model.Order,Model"/>
</set>

测试结果是:如果Customer数据库中有Orders并且Orders的lazy="false",不从缓存中获取Customer,直接从数据库中获取

NHibernate:
INSERT
INTO
Customer
(Version, Firstname, Lastname, Age)
VALUES
(@p0, @p1, @p2, @p3);
select
SCOPE_IDENTITY();
@p0 = [Type: Int32 ()],
@p1 = 'Test' [Type: String ()],
@p2 = 'TestSessionFactoryCache' [Type: String ()],
@p3 = [Type: Int32 ()]
NHibernate:
INSERT
INTO
[ Order] (
Version, OrderDate, CustomerId
)
VALUES
(@p0, @p1, @p2);
select
SCOPE_IDENTITY();
@p0 = [Type: Int32 ()],
@p1 = // :: [Type: DateTime ()],
@p2 = [Type: Int32 ()]
第1次获取数据------------------------------:
NHibernate:
SELECT
customer0_.CustomerId as CustomerId0_0_,
customer0_.Version as Version0_0_,
customer0_.Firstname as Firstname0_0_,
customer0_.Lastname as Lastname0_0_,
customer0_.Age as Age0_0_
FROM
Customer customer0_
WHERE
customer0_.CustomerId=@p0;
@p0 = [Type: Int32 ()]
NHibernate:
SELECT
orders0_.CustomerId as CustomerId1_,
orders0_.OrderId as OrderId1_,
orders0_.OrderId as OrderId1_0_,
orders0_.Version as Version1_0_,
orders0_.OrderDate as OrderDate1_0_,
orders0_.CustomerId as CustomerId1_0_
FROM
[
Order] orders0_ WHERE
orders0_.CustomerId=@p0;
@p0 = [Type: Int32 ()]
Id:-->FirtstName:Test
第2次获取数据==============================:
NHibernate:
SELECT
order0_.OrderId as OrderId1_0_,
order0_.Version as Version1_0_,
order0_.OrderDate as OrderDate1_0_,
order0_.CustomerId as CustomerId1_0_
FROM
[
Order] order0_ WHERE
order0_.OrderId=@p0;
@p0 = [Type: Int32 ()]
Id:-->FirtstName:Test
第3次获取数据==============================:
NHibernate:
SELECT
order0_.OrderId as OrderId1_0_,
order0_.Version as Version1_0_,
order0_.OrderDate as OrderDate1_0_,
order0_.CustomerId as CustomerId1_0_
FROM
[
Order] order0_ WHERE
order0_.OrderId=@p0;
@p0 = [Type: Int32 ()]
Id:-->FirtstName:Test

【2】前置条件:如果Customer数据库中有Orders并且Orders的lazy="true"

测试结果是:

NHibernate:
INSERT
INTO
Customer
(Version, Firstname, Lastname, Age)
VALUES
(@p0, @p1, @p2, @p3);
select
SCOPE_IDENTITY();
@p0 = [Type: Int32 ()],
@p1 = 'Test' [Type: String ()],
@p2 = 'TestSessionFactoryCache' [Type: String ()],
@p3 = [Type: Int32 ()]
NHibernate:
INSERT
INTO
[ Order] (
Version, OrderDate, CustomerId
)
VALUES
(@p0, @p1, @p2);
select
SCOPE_IDENTITY();
@p0 = [Type: Int32 ()],
@p1 = // :: [Type: DateTime ()],
@p2 = [Type: Int32 ()]
第1次获取数据------------------------------:
NHibernate:
SELECT
customer0_.CustomerId as CustomerId0_0_,
customer0_.Version as Version0_0_,
customer0_.Firstname as Firstname0_0_,
customer0_.Lastname as Lastname0_0_,
customer0_.Age as Age0_0_
FROM
Customer customer0_
WHERE
customer0_.CustomerId=@p0;
@p0 = [Type: Int32 ()]
Id:-->FirtstName:Test
第2次获取数据==============================:
Id:-->FirtstName:Test
第3次获取数据==============================:
Id:-->FirtstName:Test
第2次获取数据==============================:
Id:-->FirtstName:Test
第3次获取数据==============================:
Id:-->FirtstName:Test

结论:如果Customer数据库中有Orders并且Orders的lazy="true",

从缓存中获取Customer,

测试三:

测试前置条件

【1】,开启二级缓存:

<property name ="cache.use_second_level_cache" >true</property>

【2】关闭Memcashe的windows服务

01-08-05【Nhibernate (版本3.3.1.4000) 出入江湖】NHibernate二级缓存:第三方MemCache缓存

测试代码:

public void TestSessionFactoryCacheGetCustomerHavingNotOrders()
{
CustomerService customerService = new CustomerService(); Customer customer = new Customer()
{
FirstName = "Test",
LastName = "TestSessionFactoryCache",
Age =
};
customerService.Add(customer);
int customerId = customer.CustomerId; Console.WriteLine("第1次获取数据------------------------------:");
Customer customerGet1 = customerService.Get(customerId);
Console.WriteLine("Id:{0}-->FirtstName:{1}"
, customerGet1.CustomerId, customerGet1.FirstName); Console.WriteLine("第2次获取数据==============================:");
Customer customerGet2 = customerService.Get(customerId);
Console.WriteLine("Id:{0}-->FirtstName:{1}"
, customerGet2.CustomerId, customerGet2.FirstName); Console.WriteLine("第3次获取数据==============================:");
Customer customerGet3 = customerService.Get(customerId);
Console.WriteLine("Id:{0}-->FirtstName:{1}"
, customerGet3.CustomerId, customerGet3.FirstName); }

测试结果:

NHibernate:
INSERT
INTO
Customer
(Version, Firstname, Lastname, Age)
VALUES
(@p0, @p1, @p2, @p3);
select
SCOPE_IDENTITY();
@p0 = [Type: Int32 ()],
@p1 = 'Test' [Type: String ()],
@p2 = 'TestSessionFactoryCache' [Type: String ()],
@p3 = [Type: Int32 ()]
第1次获取数据------------------------------:
NHibernate:
SELECT
customer0_.CustomerId as CustomerId0_0_,
customer0_.Version as Version0_0_,
customer0_.Firstname as Firstname0_0_,
customer0_.Lastname as Lastname0_0_,
customer0_.Age as Age0_0_
FROM
Customer customer0_
WHERE
customer0_.CustomerId=@p0;
@p0 = [Type: Int32 ()]
Id:-->FirtstName:Test
第2次获取数据==============================:
NHibernate:
SELECT
customer0_.CustomerId as CustomerId0_0_,
customer0_.Version as Version0_0_,
customer0_.Firstname as Firstname0_0_,
customer0_.Lastname as Lastname0_0_,
customer0_.Age as Age0_0_
FROM
Customer customer0_
WHERE
customer0_.CustomerId=@p0;
@p0 = [Type: Int32 ()]
Id:-->FirtstName:Test
第3次获取数据==============================:
NHibernate:
SELECT
customer0_.CustomerId as CustomerId0_0_,
customer0_.Version as Version0_0_,
customer0_.Firstname as Firstname0_0_,
customer0_.Lastname as Lastname0_0_,
customer0_.Age as Age0_0_
FROM
Customer customer0_
WHERE
customer0_.CustomerId=@p0;
@p0 = [Type: Int32 ()]
Id:-->FirtstName:Test

测试三的结论:

启用Nhibernate的二级缓存并且关闭Memcashe的windows服务。不会抛出异常,而是直接从数据库读取数据,当这个缓存不存在,

容错能力还是很强大的呀!

源码下载:

链接: http://pan.baidu.com/s/1dDGmcYd 密码: eqj3

上一篇:TC SRM 584 DIV2


下一篇:整理php操作memcache缓存为基础的方法