01-08-02【Nhibernate (版本3.3.1.4000) 出入江湖】二级缓存:NHibernate自带的HashtableProvider...

 

 

第一步骤: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 1, false 0, yes 'Y', no 'N'</property>     <!--=======加入Nhibernate自身的HashtabeCache的二级缓存配置=============================--><!--1.配置二级缓存提供程序--><property name="cache.provider_class">NHibernate.Cache.HashtableCacheProvider</property><!--2.显式启用二级缓存--><property name ="cache.use_second_level_cache">true</property><!--4.启动查询缓存--><property name="cache.use_query_cache">true</property><!--实体类所在的程序集--><mapping assembly="Model"/><!--3.配置映射的二级缓存--><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="0" lazy="false"><!--1.这个不是必须的,因为在nhibernate.cfg.xml文件中已经有了一个总配置2.cache标签必须在id标签前面--><cache usage="read-write"/><!--unsaved-value="0" 主键表中不需要定义,而是需要在子表中定义--><id name="CustomerId"column="CustomerId"type="int" unsaved-value="0"><generator class="native" /><!-- unsaved-value used to be null and generator was increment in h2.0.3 --></id>
。。。。。。。。。。。。。。。<set name="Orders" table="Order"  lazy="true"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:

       二级缓存与Get方法+Lazy设置的关系:

测试图解:


 

 

经测试,得出如下结论:

 

Get方法+Lazy配置+二级缓存测试结果:

                                         Customer.hbm.xml的<Set name="Orders"        Customer.hbm.xml的<Set name="Orders"       

                                                          lazy="true">                   lazy="false">      

                                                         <cache usage="read-write"/>                      <cache usage="read-write"/>

 

Customer数据库中Order个数等于零                   Get方法从二级缓存获取Customer                               Get方法从二级缓存获取Customer 

Customer数据库中Order个数大于零                   Get方法从二级缓存获取Customer                               Get方法从不从二级缓存获取Customer 

 

 

 

------------------------更新二级缓存测试---------------------------------------------------------------

测试更新-1:

前置条件:

1.Customer没Orders

2.

  <class name="Model.Customer, Model"table="Customer"discriminator-value="0" lazy="true"><!--1.这个不是必须的,因为在nhibernate.cfg.xml文件中已经有了一个总配置2.cache标签必须在id标签前面--><cache usage="read-write"/>

测试代码:

 

        [TestMethod]public void TestSessionFactoryCacheUpdateCustomerHavingNotOrders(){CustomerService customerService = new CustomerService();Customer customer = new Customer(){FirstName = "Test",LastName = "TestSessionFactoryCache",Age = 10};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);customerGet1.FirstName = "我是更新后的FirstName"; //修改FirstNamecustomerService.Update(customerGet1);  //保存更新得到数据库。
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);}
View Code

 

测试结果:

NHibernate: INSERT INTOCustomer(Version, Firstname, Lastname, Age) VALUES(@p0, @p1, @p2, @p3);selectSCOPE_IDENTITY();@p0 = 1 [Type: Int32 (0)],@p1 = 'Test' [Type: String (4000)],@p2 = 'TestSessionFactoryCache' [Type: String (4000)],@p3 = 10 [Type: Int32 (0)]
第1次获取数据并且更新------------------------------:
NHibernate: SELECTcustomer0_.CustomerId as CustomerId0_0_,customer0_.Version as Version0_0_,customer0_.Firstname as Firstname0_0_,customer0_.Lastname as Lastname0_0_,customer0_.Age as Age0_0_ FROMCustomer customer0_ WHEREcustomer0_.CustomerId=@p0;@p0 = 198 [Type: Int32 (0)]
NHibernate: SELECTorders0_.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_ WHEREorders0_.CustomerId=@p0;@p0 = 198 [Type: Int32 (0)]
更新前:Id:198-->FirtstName:Test
NHibernate: UPDATECustomer SETVersion = @p0,Firstname = @p1,Lastname = @p2,Age = @p3 WHERECustomerId = @p4 AND Version = @p5;@p0 = 2 [Type: Int32 (0)], @p1 = '我是更新后的FirstName' [Type: String (4000)], @p2 = 'TestSessionFactoryCache' [Type: String (4000)], @p3 = 10 [Type: Int32 (0)], @p4 = 198 [Type: Int32 (0)], @p5 = 1 [Type: Int32 (0)]
更新后:Id:198-->FirtstName:我是更新后的FirstName
第2次获取数据==============================:
Id:198-->FirtstName:我是更新后的FirstName
第3次获取数据==============================:
Id:198-->FirtstName:我是更新后的FirstName
View Code

 

 

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

测试更新-2

前置条件:

1.Customer有Orders

2.

    <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>

 

测试代码和结果:表明2级缓存失效

        [TestMethod]public void TestSessionFactoryCacheUpdateCustomerHavingOrders(){CustomerService customerService = new CustomerService();Customer customer = new Customer(){FirstName = "Test",LastName = "TestSessionFactoryCache",Age = 10};Order order1 = new Order(){OrderDate = DateTime.Now,Customer = customer};customer.Orders.Add(order1);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);customerGet1.FirstName = "我是更新后的FirstName"; //修改FirstNamecustomerService.Update(customerGet1);  //保存更新得到数据库。
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);}
View Code
NHibernate: INSERT INTOCustomer(Version, Firstname, Lastname, Age) VALUES(@p0, @p1, @p2, @p3);selectSCOPE_IDENTITY();@p0 = 1 [Type: Int32 (0)],@p1 = 'Test' [Type: String (4000)],@p2 = 'TestSessionFactoryCache' [Type: String (4000)],@p3 = 10 [Type: Int32 (0)]
NHibernate: INSERT INTO[Order] (Version, OrderDate, CustomerId) 
VALUES(@p0, @p1, @p2);selectSCOPE_IDENTITY();@p0 = 1 [Type: Int32 (0)],@p1 = 2014/5/29 23:15:57 [Type: DateTime (0)],@p2 = 199 [Type: Int32 (0)]
第1次获取数据并且更新------------------------------:
NHibernate: SELECTcustomer0_.CustomerId as CustomerId0_0_,customer0_.Version as Version0_0_,customer0_.Firstname as Firstname0_0_,customer0_.Lastname as Lastname0_0_,customer0_.Age as Age0_0_ FROMCustomer customer0_ WHEREcustomer0_.CustomerId=@p0;@p0 = 199 [Type: Int32 (0)]
NHibernate: SELECTorders0_.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_ WHEREorders0_.CustomerId=@p0;@p0 = 199 [Type: Int32 (0)]
更新前:Id:199-->FirtstName:Test
NHibernate: UPDATECustomer SETVersion = @p0,Firstname = @p1,Lastname = @p2,Age = @p3 WHERECustomerId = @p4 AND Version = @p5;@p0 = 2 [Type: Int32 (0)], @p1 = '我是更新后的FirstName' [Type: String (4000)], @p2 = 'TestSessionFactoryCache' [Type: String (4000)], @p3 = 10 [Type: Int32 (0)], @p4 = 199 [Type: Int32 (0)], @p5 = 1 [Type: Int32 (0)]
NHibernate: UPDATE[Order] SETVersion = @p0,OrderDate = @p1,CustomerId = @p2 WHEREOrderId = @p3 AND Version = @p4;@p0 = 2 [Type: Int32 (0)], @p1 = 2014/5/29 23:15:57 [Type: DateTime (0)], @p2 = 199 [Type: Int32 (0)], @p3 = 34 [Type: Int32 (0)], @p4 = 1 [Type: Int32 (0)]
更新后:Id:199-->FirtstName:我是更新后的FirstName
第2次获取数据==============================:
NHibernate: SELECTorder0_.OrderId as OrderId1_0_,order0_.Version as Version1_0_,order0_.OrderDate as OrderDate1_0_,order0_.CustomerId as CustomerId1_0_ FROM[Order] order0_ WHEREorder0_.OrderId=@p0;@p0 = 34 [Type: Int32 (0)]
Id:199-->FirtstName:我是更新后的FirstName
第3次获取数据==============================:
NHibernate: SELECTorder0_.OrderId as OrderId1_0_,order0_.Version as Version1_0_,order0_.OrderDate as OrderDate1_0_,order0_.CustomerId as CustomerId1_0_ FROM[Order] order0_ WHEREorder0_.OrderId=@p0;@p0 = 34 [Type: Int32 (0)]
Id:199-->FirtstName:我是更新后的FirstName
View Code

 

将该测试(测试更新-2)的前置条件2改为:

lazy="true"  ,即修改后的配置如下:  
    <set name="Orders" table="Order"  lazy="true"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>

 

lazy="true" 时,2级缓存生效,测试结果如下所示:
NHibernate: INSERT INTOCustomer(Version, Firstname, Lastname, Age) VALUES(@p0, @p1, @p2, @p3);selectSCOPE_IDENTITY();@p0 = 1 [Type: Int32 (0)],@p1 = 'Test' [Type: String (4000)],@p2 = 'TestSessionFactoryCache' [Type: String (4000)],@p3 = 10 [Type: Int32 (0)]
NHibernate: INSERT INTO[Order] (Version, OrderDate, CustomerId) 
VALUES(@p0, @p1, @p2);selectSCOPE_IDENTITY();@p0 = 1 [Type: Int32 (0)],@p1 = 2014/5/29 22:55:43 [Type: DateTime (0)],@p2 = 193 [Type: Int32 (0)]
第1次获取数据并且更新------------------------------:
NHibernate: SELECTcustomer0_.CustomerId as CustomerId0_0_,customer0_.Version as Version0_0_,customer0_.Firstname as Firstname0_0_,customer0_.Lastname as Lastname0_0_,customer0_.Age as Age0_0_ FROMCustomer customer0_ WHEREcustomer0_.CustomerId=@p0;@p0 = 193 [Type: Int32 (0)]
更新前:Id:193-->FirtstName:Test
NHibernate: UPDATECustomer SETVersion = @p0,Firstname = @p1,Lastname = @p2,Age = @p3 WHERECustomerId = @p4 AND Version = @p5;@p0 = 2 [Type: Int32 (0)], @p1 = '我是更新后的FirstName' [Type: String (4000)], @p2 = 'TestSessionFactoryCache' [Type: String (4000)], @p3 = 10 [Type: Int32 (0)], @p4 = 193 [Type: Int32 (0)], @p5 = 1 [Type: Int32 (0)]
更新后:Id:193-->FirtstName:我是更新后的FirstName
第2次获取数据==============================:
Id:193-->FirtstName:我是更新后的FirstName
第3次获取数据==============================:
Id:193-->FirtstName:我是更新后的FirstName
View Code

 

经测试,得出如下结论:

 

Update方法+Get方法+Lazy配置+二级缓存测试结果:

                                         Customer.hbm.xml的<Set name="Orders"                 Customer.hbm.xml的<Set name="Orders"       

                                                          lazy="true">                   lazy="false">      

                                                         <cache usage="read-write"/>                      <cache usage="read-write"/>

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

Customer数据库中Order个数等于零                 用 Update方法Customer后,                           用 Update方法Customer后,

                                                                Get方法从二级缓存获取Customer                     Get方法从二级缓存获取Customer 

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

Customer数据库中Order个数大于零                   用 Update方法Customer后                              用 Update方法Customer后

                                Get方法从二级缓存获取Customer                        Get方法从不从二级缓存获取Customer  

 

 

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

 

 

转载于:https://www.cnblogs.com/easy5weikai/p/3759277.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/493195.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2018, 自动驾驶异常艰难的一年

编译&#xff1a;张玺 &#xff0c;编辑&#xff1a;宇多田摘要&#xff1a;虽然文章几乎聚焦于美国硅谷的技术公司&#xff0c;但这并不意味着作者提出的种种问题不存在于中国的技术公司身上。有意思的是&#xff0c;作者批评了各大公司此前疯狂立 flag&#xff0c;却最后纷纷…

目标检测矩形框与polygon数据增加--裁剪,拓展,旋转

1.裁剪 import torch from torchvision import transforms import cv2 import numpy as np import types from numpy import random class RandomSampleCrop(object):"""CropArguments:img (Image): the image being input during trainingboxes (Tensor): th…

医生们说,AI不会取代我们!

来源&#xff1a;IEEE电气电子工程师学会每次人工智能在医疗任务中与医生进行竞争&#xff08;对此我们已经报道过很多次&#xff09;时&#xff0c;一个问题不可避免地浮出水面&#xff1a;人工智能会取代医生吗&#xff1f;如果你与AI 专家或硅谷投资者交谈&#xff0c;答案往…

ubuntu安装python3.5+pycharm+anaconda+opencv+docker+nvidia-docker+tensorflow+pytorch+Cmake3.8

一&#xff0c;切换python版本为3.5 装好ubuntu&#xff0c;python版本是2.7的 我自己安装并更改打开为python3.5 sudo apt-get install python3.5 设置优先级和默认环境&#xff1a; sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 100 su…

学界 | 量化深度强化学习算法的泛化能力

来源&#xff1a;AI 科技评论OpenAI 近期发布了一个新的训练环境 CoinRun&#xff0c;它提供了一个度量智能体将其学习经验活学活用到新情况的能力指标&#xff0c;而且还可以解决一项长期存在于强化学习中的疑难问题——即使是广受赞誉的强化算法在训练过程中也总是没有运用监…

《科学》评出2018年度十大科学突破事件

来源&#xff1a;科学大院《科学》杂志每年会评出在即将过去的一年里最为重要的十大科学突破&#xff08;Science Breakthrough&#xff09;。今年&#xff0c;夺得年度突破桂冠的是“单细胞水平细胞谱系追踪技术”&#xff0c;帮助破获多起悬案的法医系谱技术、#MeToo 运动等也…

递归理解以及时间复杂度计算

一.复杂度分析&#xff1a; 可以理解为递归的深度就是空间复杂度&#xff0c;时间复杂度就是O(T*depth),其中&#xff34;是每个递归函数的时间复杂度&#xff0c;depth是递归深度&#xff0e; #空间复杂度O(1) def sum1_(n):res 0for i in range(n1):resireturn res#递归 空…

性价比高出英特尔45%,亚马逊的云服务器芯片如何做到?| 解读

来源&#xff1a;TheNextPlatform编译&#xff1a;机器之能 张玺摘要&#xff1a;到目前为止&#xff0c;亚马逊和其他大型云运营商几乎全部使用英特尔的 Xeon 芯片。虽然在服务器芯片市场&#xff0c;英特尔市场占有率非常高&#xff0c;但亚马逊正使用折扣策略来赢得客户。亚…

GIOU loss+DIOU loss+CIOU loss

一.IOU 1.GIOU解决没有交集的框,IOU为0,其损失函数导数为0,无法优化的问题。 图1 GIOU,IOU,l2范数差异 a)可看出 l2值一样,IOU值是不一样的,说明L1,L2这些Loss用于回归任务时&#xff0c;不能等价于最后用于评测检测的IoU. b)可看出当框有包含关系,GIOU就退化为IOU 其是找…

《科学》十大年度科学突破反映的新动向

来源&#xff1a;新华网摘要&#xff1a;从测定分子结构到宇宙探索&#xff0c;从发现远古动物到揭示细胞的秘密&#xff0c;美国权威学术刊物《科学》杂志评选的2018年十大科学突破&#xff0c;在时间和空间尺度上拓宽着人类认知的边界&#xff0c;也反映了近年来科学发展的三…

ctpn论文阅读与代码

代码地址: https://github.com/zonghaofan/ctpn_torch 1.通用的目标检测是封闭的,而文字是封闭且连续 2. 构造一系列宽度相等的小文本,回归中心y坐标和高度 3. 对于边界回归x坐标,在进一次修正 4.整个模型就是backbone提取特征,将每个像素点的相邻3*3像素拉成行向量,利用空间…

yum配置与使用

yum配置与使用(很详细) yum的配置一般有两种方式&#xff0c;一种是直接配置/etc目录下的yum.conf文件&#xff0c;另外一种是在/etc/yum.repos.d目录下增加.repo文件。一、yum的配置文件$ cat /etc/yum.conf [main]cachedir/var/cache/yum #yum下载的RPM包的缓存目录k…

新技术不断涌现,下一代云计算的突破口在哪里?

来源&#xff1a;日知录技术社区这是一个IT技术飞速发展的时代&#xff0c;在硬件基础设施的不断升级以及虚拟化网络等技术的日益成熟下&#xff0c;云厂商也正面临着各种新技术带来的巨大挑战。从数据中心的基础建设到云平台的系统构建再到产品底层的技术改革&#xff0c;该如…

生成高斯热力图(craft中有使用)+2d heatmap+3d heatmap

一.生成高斯热力图 from math import exp import numpy as np import cv2 import osclass GaussianTransformer(object):def __init__(self, imgSize512, region_threshold0.4,affinity_threshold0.2):distanceRatio 3.34scaledGaussian lambda x: exp(-(1 / 2) * (x ** 2))…

POP动画[1]

POP动画[1] pop动画是facebook扩展CoreAnimation的,使用及其方便:) 1:Spring系列的弹簧效果(两个动画kPOPLayerBounds与kPOPLayerCornerRadius同时运行) #import "RootViewController.h" #import "YXEasing.h" #import "POP.h" #import "YX…

远比5G发展凶猛!物联网2018白皮书,国内规模已达1.2万亿

来源&#xff1a;智东西摘要&#xff1a;研判物联网的技术产业进展情况&#xff0c;梳理消费物联网、智慧城市物联网、生产性物联网三类物联网应用现状及驱动因素 。在供给侧和需求侧的双重推动下&#xff0c;物联网进入以基础性行业和规模消费为代表的第三次发展浪潮。 5G、 低…

收缩分割多边形(PSENet中有使用)

目的:为了解决密集文本的分割问题 代码: # -*- codingutf-8 -*- import os import cv2 import Polygon as plg import pyclipper import numpy as npdef dist(a, b):return np.sqrt(np.sum((a - b) ** 2))#计算周长 def perimeter(bbox):peri 0.0for i in range(bbox.shape[…

Android 3D emulation 架构理解

Android Emulator 给用户提供 GPU on 选项&#xff0c;意思是利用 Host ( 就是执行 Emulator 的PC机) 的 GPU. 当然PC机必须把 OpenGL 的驱动装好 在实现上就是把 libGLESv1_CM.so libGLESv2.so 替换掉&#xff0c;当system调用 gl的函数的时候&#xff0c;把调用打包为strea…

年度回顾:2018年的人工智能/机器学习惊喜及预测19年的走势

来源&#xff1a;网络大数据考虑到技术变革的速度&#xff0c;我认为让专业IT人士分享他们对2018年最大惊喜及2019年预测的看法会很有趣。以下是他们对人工智能(AI)&#xff0c;机器学习( ML)和其他数据科学迭代的看法&#xff1a;CLARA分析公司首席执行官兼创始人&#xff1a;…

利用dbnet分割条形码与文字(代码+模型)+知识蒸馏+tensorrt推理+利用pyzbar和zxing进行条形码解析

一.DBnet 1.代码链接 分割条形码与文字代码:github链接:GitHub - zonghaofan/dbnet_torch: you can use dbnet to detect word or bar code,Knowledge Distillation is provided,also python tensorrt inference is provided.&#xff08;提供模型&#xff09; 2.论文阅读 …