该用户从未签到
需要启动二级缓存,二级缓存的scope是sessionFactory。也就是说二级缓存的数据可以在由相同SessionFactory创建的多个Session中重用。
6 c# W+ w g1 k " ^0 D6 s% j- K. t1 P
首先,要在hibernate .cfg.xml中设置一个cache Provider,hibernate支持多个cache实现,有EHCache,OSCache等。在非分布式环境中可以选择默认的EHCache。添加ehcahe jar
8 J( B5 H# I1 Z9 t. ?5 P* c. F. s <dependency>
8 v( W% g/ s! f5 K <groupId>org.hibernate</groupId>) y2 X- g* Z9 _# Q' f+ a( A
<artifactId>hibernate-ehcache</artifactId>: m! U& `" s8 e! A& C3 F+ h
<version>4.3.5.Final</version>6 \/ T. r, i$ H: ]
</dependency> 复制代码 <hibernate-configuration>
% |$ _3 x* L- G7 z( k <session-factory>8 t0 y4 A7 ?; ]* j
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>8 s4 a( N! A4 e/ J3 z
<property name="connection.url">jdbc:mysql://localhost/test</property>
) ?2 T+ s- Z9 D4 k2 j9 N <property name="connection.username">root</property>; g" \8 y: v) l1 U- R
<property name="connection.password"></property>
- }+ a/ A [1 ]) v$ @* f <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>; ~& u1 W+ Z* h/ z8 Q. Z$ [
<property name="hibernate.show_sql">true</property>8 y! b. V8 m& Z2 t, Y7 |1 X
<property name="hibernate.hbm2ddl.auto">update</property>: W9 P& i, b$ w& A! }8 a* {
<property name="hibernate.generate_statistics">true</property>- [% @# a2 A" G. p1 N" D
<property name="hibernate.cache.region.factory_class">/ u; f( C3 K, A `2 @
org.hibernate.cache.ehcache.EhCacheRegionFactory# V! h5 u* M$ J6 e
</property>+ Y: J$ E$ S2 T! D1 U! ^. \
<mapping class="com.xinglongjian.entity.hbm.Book2"/>$ g; y$ p8 w- C ^
</hibernate-configuration> 复制代码 ' W- u( r, F F7 j9 Q( f
第二,通过ehcache.xml配置EHCache,该文件放置于classpath的根目录下。可以在该配置文件中设置将不同的对象存储在不同的regions。<ehcache>
0 e% a) p$ _: a4 z; L, P$ h% P# G <diskStore path="c:/data/ehcache"/># u9 v7 s& D, i2 c" N. [/ ]
<defaultCache1 c7 c' k5 V9 w
maxElementsInMemory="10"& a8 T1 y1 k2 e
eternal="false"
; f i# ~. c4 U overflowToDisk="true"
/ p- j! v$ p/ m) f5 O7 X, q timeToIdleSeconds="120"
]* \: b( c% ?; E, V4 r/ ^; f timeToLiveSeconds="120"
* }$ x/ c% k& S# ]6 |* D2 H3 F diskPersistent="false"2 j7 ~. J0 W* G: ~; Q
diskExpiryThreadIntervalSeconds="120"/>4 a, B% e( e2 |/ Z
<cache name="com.xinglongjian.entity.hbm.Book" maxElementsInMemory="10" eternal="false"
1 f1 @& ], G' S* B8 s overflowToDisk="false" timeToIdleSeconds="120" timeToLiveSeconds="120" diskPersistent="false"/> u1 `5 ?! U" T; x# P, S# j
</ehcache> 复制代码 第三,设置持久化类@Entity! m7 E3 |& G5 N9 M
@Cacheable
4 O; M+ V% n$ A6 a- e$ E: i: R @Cache(usage=CacheConcurrencyStrategy.READ_ONLY,region="com.xinglongjian.entity.hbm.Book"), V6 F( D) q" V9 G+ E
public class Book2 {* P. M! X; ]9 N; M. }" \
@Id
# F$ Y1 j' a. d; J- `( M @GeneratedValue5 C: B% _+ J$ u0 f
private int id;
8 c" ~: O# x% a- a& \ private String title;2 e1 [8 Q1 p: L! F9 b I
public String getTitle() {
% a7 I# K3 D& |' Q6 Y return title;
" T4 ^8 ^2 ?$ T' k, \. n0 ] }0 i- o9 _$ t$ Y. h2 C5 i! E
public void setTitle(String title) {* n% t z% G. ~- I
this.title = title;
- D/ Q- R+ P! I. l1 P }9 V% O+ Y D4 O4 I
public int getId() {4 H1 Y) S0 a# x- \+ y8 p
return id;% A, n8 t. j) T& w f1 ^4 y
}( f9 t" h5 T: R' _' p& r- o% c
public void setId(int id) {
, j' B( s$ y* h% ^, K this.id = id;( y4 x$ T6 D" H/ [+ [5 Q& b
}& p" ?3 j# Z0 j/ O; j7 R$ K
@Override& G6 B8 z+ w# ? W
public int hashCode() {% F+ W0 i) W) H5 H/ h) [3 r
final int prime = 31;; y8 C1 S0 F& r
int result = 1;- e, q' _6 w6 V, X" C' ]3 p
result = prime * result + id;
! |9 U! G& R1 N& x' p result = prime * result + ((title == null) ? 0 : title.hashCode());
/ R5 C3 Q8 ^! ~# N1 L5 q4 S, o4 u return result;. l! S. g: f5 F: J1 b" U2 n+ G
}
% L6 L3 }7 d3 B @Override
- T4 Z2 ]; J& M" ~( a public boolean equals(Object obj) {
9 K C2 u* | T2 @) U2 k, x( h7 k if (this == obj)7 }6 b9 A j; p4 B* |
return true;
0 }5 a3 |4 a+ I4 w' e" }3 x6 S if (obj == null)/ S* V7 ]$ Q0 Z1 U$ _: S
return false;# X" z5 m8 U3 ^- w" P# X1 Q' U
if (getClass() != obj.getClass())
+ c. f+ a" f+ s return false;" [. l5 y7 P6 @8 ~& R9 u; X9 q5 G
Book2 other = (Book2) obj;$ I. o1 p `9 c+ R- L; l5 |' c8 H% T# ^
if (id != other.id)" S# C, z- b8 s
return false;& m" m1 _* W; b' t% g: k ~1 S' R
if (title == null) {; C, v) R6 L9 j( q0 H
if (other.title != null)
2 u% w7 _) n5 a+ O H3 K1 K3 o return false;
, c; M0 `+ N: Y' ]. w } else if (!title.equals(other.title))
/ Q, n4 u0 v/ Y/ g* K5 M2 u4 G return false;
. p: [. H$ [1 u return true;/ C3 t& A! R. L7 i. Y( G) U
}% I- C8 u7 O, b3 C+ J
" b7 _) I' f! l6 ]/ a
} 复制代码 二级缓存的持久化类必须实现equals方法。
+ L" @. X5 ^* m/ N5 p* L) A& z 7 F) y0 [* j5 H
只有在SELECT时才会缓存。0 \* S& C' x, X# C
) c2 e, d6 f' ^, d" b 在同一个session里,查询2个不同的对象,会缓存2次,Session sess=sf.openSession();
$ v( U; W) ?, x4 h' D7 V% O. L Book2 b=(Book2) sess.get(Book2.class, 17);, k. s9 w9 I% Z L8 ^7 @8 w. v
System.out.println(b);0 `5 h' K8 k& B. C; T; M" w" p
assertEquals("spring Recipes", b.getTitle());
" n$ z0 c- a: x Book2 b3=(Book2) sess.get(Book2.class, 18);; d, O* E3 m3 h7 M& e6 |& j
assertEquals("dfad", b3.getTitle());
- E4 K' { K" P sess.close();
4 T5 a( p% c! S1 s' U7 `# y. A slcs=stat.getSecondLevelCacheStatistics("com.xinglongjian.entity.hbm.Book");$ b2 e; n- g" i( p- U, H, r7 p
System.out.println(slcs); 复制代码 结果SecondLevelCacheStatistics[hitCount=0,missCount=2,putCount=2,elementCountInMemory=2,elementC5 J1 c5 F; e9 D7 `
ountOnDisk=0,sizeInMemory=3948] 复制代码
" [' ?2 ] o) b* ` 在同一个session里,查询相同的对象,会先查询一级缓存,一级缓存中有就不会查询二级缓存。Session sess1=sf.openSession();
) G7 x* ~/ ]! w. ] V1 n Book2 b1=(Book2) sess1.get(Book2.class, 17);/ U) `" m2 C# k, C+ N& m F
System.out.println(b);6 e' B- i+ s4 \+ _
Book2 b2=(Book2) sess1.get(Book2.class, 17);
2 a: e% O* `; e h0 `# U) E assertEquals("Spring Recipes", b1.getTitle());
4 t% B# O6 g$ D1 @' l( ?/ p T assertEquals("Spring Recipes", b2.getTitle());3 ?) s$ M% E' @# v& ^' a
slcs=stat.getSecondLevelCacheStatistics("com.xinglongjian.entity.hbm.Book");
' |- M& ~; T: A* J5 e6 [ System.out.println(slcs); 复制代码 结果,在新的session中,一级缓存不可用,就会使用二级缓存。SecondLevelCacheStatistics[hitCount=1,missCount=2,putCount=2,elementCountInMemory=2,elementC% H3 s) [. C' G
ountOnDisk=0,sizeInMemory=3948] 复制代码 完整测试逻辑@Test9 g* g& q. W/ X! E. D. s
public void test2LCache()
/ z+ B* P2 J | {' h. o4 B! W. m8 f5 W+ w
Statistics stat=sf.getStatistics();//获取stat对象
8 N* Y# o; c5 T* A. k2 U! }6 t Session sess=sf.openSession();& F) J1 K0 E3 W2 @+ b. M1 _$ a
Transaction tx=sess.beginTransaction();
) I4 B, n1 R% t) r, q% a) N. x
- E" w# M- C/ f5 p- c" ~8 _4 i //存储对象,此时不会放到缓存中% n1 b. G2 U* [
System.out.println("--------------存储对象---------------------------------");
5 e. D# j( c3 D9 }) k! e1 \ Book2 book=new Book2();
5 A. c* W# Z* a1 |9 w1 _& ? book.setTitle("Spring Recipes");. W! g; K8 Y/ W
sess.saveOrUpdate(book);( @. p8 k# I( h0 O+ Q: o4 X- x
tx.commit();. p L" O' W9 \6 l* V9 E* r
sess.close();( y, I' t8 N+ C- s
System.out.println(book);4 O4 {/ c4 J# ~, |9 ]
SecondLevelCacheStatistics slcs=stat.getSecondLevelCacheStatistics("com.xinglongjian.entity.hbm.Book");6 f% f# l7 S- R/ q7 T
System.out.println(slcs);& }$ m% A0 C3 y! @
Cache cache=sf.getCache();* V K* }9 H* e# S2 L
System.out.println(cache);
/ _7 I6 ]( x- c- _3 x; t cache.evictAllRegions();//从所有region中获取数据
+ q0 E( X5 W: P2 o+ R9 j Map map=slcs.getEntries();
8 d& ?1 s- i7 s' a9 ^ System.out.println("Cache entries:"+map.size());
; @9 U! F3 h2 z5 S) D) O" E3 M8 b System.out.println("--------------第一次查询后---------------------------------");0 l( \/ Z' @# ^) x2 U& k0 h r
sess=sf.openSession();
; A) O+ M; q9 O) k* K- B tx=sess.beginTransaction();
1 }0 g, k* Z4 P( q/ c4 ?4 G# f- g Book2 b1=(Book2) sess.byId(Book2.class).load(book.getId());//第一次查询6 E0 J" @( A& v: t* _
System.out.println(b1);8 F9 P) L, C1 Q& J0 {
assertEquals(book, b1);
4 S7 k) K+ |5 s, |: Y5 m4 e# S tx.commit();% ?" O4 }' l. d$ M
sess.close();# H5 Z! E1 d( {8 C. e( h: h
slcs=stat.getSecondLevelCacheStatistics("com.xinglongjian.entity.hbm.Book");% U/ X0 i& R7 m' o# L2 O
System.out.println(slcs);
8 P; t- O4 @3 ~8 Y map=slcs.getEntries();
+ h# q$ M) y4 E$ K* R System.out.println(map.size());) J d8 C/ B7 O, h1 V
System.out.println("--------------第二次查询后---------------------------------");
; h9 u2 t4 I8 | sess=sf.openSession();
+ l/ a: ?4 G, G' {7 r; ?9 F tx=sess.beginTransaction();
+ g& X. J) p6 A Book2 b2=(Book2) sess.byId(Book2.class).load(book.getId());//第二次查询
% { E+ o8 ~) \. K System.out.println(b2);
' }. d3 R, m* j1 A assertEquals(book, b2);
: {$ s+ p2 w t/ ] tx.commit();7 Q, e1 C3 O3 f# j
sess.close();8 t( H! a; r9 d4 B( j
7 m9 Z$ a% z" z2 D: V1 U0 P
slcs=stat.getSecondLevelCacheStatistics("com.xinglongjian.entity.hbm.Book");
0 Z5 j. s5 z D System.out.println(slcs);& }- W, v$ r8 y9 X
// this is the initial select
% v! I0 e4 u5 C8 T7 N/ r assertEquals(stat.getSecondLevelCacheMissCount(), 1);) `( z' r- s/ X! w
// we put one element in the cache from the miss
0 s! _& S6 W& X, ^0 |3 K% J* v assertEquals(stat.getSecondLevelCachePutCount(), 1);, b: |0 Q6 s: L3 @; I i
// we still didn't hit the cache, because of 1L cache* I3 ~' u7 u4 ~, p
assertEquals(stat.getSecondLevelCacheHitCount(), 1);' G p; q; y9 t1 l' F
System.out.println("--------------第三次查询后---------------------------------");
! z& J, w8 a* }! L$ v0 a sess=sf.openSession();
& P4 m3 g# }" ? R2 O6 f tx=sess.beginTransaction();6 A% s9 W# d9 Q- _1 v
b1=(Book2) sess.byId(Book2.class).load(book.getId());//第三次查询- z, c) b: U: [7 V
assertEquals(book, b1);
- m$ L+ s( V$ c, ~6 i2 i# A tx.commit();8 \" d( I$ n' x5 J- U5 M
sess.close();- S* T# C( _& S" J6 O
2 V# o5 Q' d; | Z0 T, G! I slcs=stat.getSecondLevelCacheStatistics("com.xinglongjian.entity.hbm.Book");) M; j3 W' u6 m6 h$ S1 X: z+ i
System.out.println(slcs);
: B2 X6 L+ V) i$ X m // same miss count (we should hit now)
# x( U" Y e/ q7 L7 d, Y assertEquals(stat.getSecondLevelCacheMissCount(), 1);
. P, W8 R; J! q // same put count (we didn't put anything new)
; y9 [8 C d9 I$ i5 a1 M3 h assertEquals(stat.getSecondLevelCachePutCount(), 1);
" f/ A. Y5 G2 I4 C+ t5 L' A // now we hit the 2L cache for load
& R+ n$ ]8 y6 X5 k3 T) E assertEquals(stat.getSecondLevelCacheHitCount(), 2);( u" \" P0 A3 E* R+ o+ Y
" s. `* X/ S$ V4 w0 \# M } 复制代码 完整测试结果Hibernate: delete from book2
7 U: v l E6 g; C --------------存储对象---------------------------------% O/ ~' E2 f5 `9 R; a8 b
Hibernate: insert into Book2 (title) values (?)
5 z- L$ O" J7 H; w0 d" C D, F com.xinglongjian.entity.hbm.Book2@521e083b2 Q: [% x$ J2 ?3 V. I3 n* o, ~1 e
SecondLevelCacheStatistics[hitCount=0,missCount=0,putCount=0,elementCountInMemory=0,elementCountOnDisk=0,sizeInMemory=0]' I& ?' Q& a2 V( C* X& ]
org.hibernate.internal.CacheImpl@4830f6
9 f C, j/ r h' T. Q: I Cache entries:0+ N ]7 \1 B. [" t: M1 C
--------------第一次查询后---------------------------------
1 K" F4 {0 l% P* ?4 t Hibernate: select book2x0_.id as id1_0_0_, book2x0_.title as title2_0_0_ from Book2 book2x0_9 k! D7 H. x( l6 |; w
where book2x0_.id=?6 {! s" b" L6 @; ]
com.xinglongjian.entity.hbm.Book2@521e083b; Y$ {; E/ s6 A8 r+ h, f
SecondLevelCacheStatistics[hitCount=0,missCount=1,putCount=1,elementCountInMemory=1,elementC- L& {1 K) f: h6 d+ ]
ountOnDisk=0,sizeInMemory=1979]8 B7 }8 b3 t) X3 {
17 m# Z/ \4 P0 K1 U) _1 x& s
--------------第二次查询后---------------------------------
& B- o! h' F& k- X7 g, t com.xinglongjian.entity.hbm.Book2@521e083b
" _% w2 f5 W& ^ ]" F2 V! y3 M SecondLevelCacheStatistics[hitCount=1,missCount=1,putCount=1,elementCountInMemory=1,elementC) E( u0 {! B% K
ountOnDisk=0,sizeInMemory=1979]
: N5 C% e& ` w: v3 H, P) z --------------第三次查询后---------------------------------0 L# }7 D4 G6 k% i# i) N' |. p9 z
SecondLevelCacheStatistics[hitCount=2,missCount=1,putCount=1,elementCountInMemory=1,elementC
, ^. L4 V6 H3 G V. X3 K ountOnDisk=0,sizeInMemory=1979] 复制代码
% D- k0 y$ r4 C' @- B, a3 K$ ]5 A
科帮网 1、本主题所有言论和图片纯属会员个人意见,与本社区立场无关2、本站所有主题由该帖子作者发表,该帖子作者与科帮网 享有帖子相关版权3、其他单位或个人使用、转载或引用本文时必须同时征得该帖子作者和科帮网 的同意4、帖子作者须承担一切因本文发表而直接或间接导致的民事或刑事法律责任5、本帖部分内容转载自其它媒体,但并不代表本站赞同其观点和对其真实性负责6、如本帖侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意7、科帮网 管理员和版主有权不事先通知发贴者而删除本文
JAVA爱好者①群:
JAVA爱好者②群:
JAVA爱好者③ :