接上例:http://www.bianceng.cn/Programming/Java/201101/23637.htm
修改BusinessService.java文件如下所示:
1.package com.hb3.pack_01;
2.
3.import org.hibernate.Session;
4.import org.hibernate.SessionFactory;
5.import org.hibernate.cfg.Configuration;
6.
7.import com.hb3.pack_01.model.User;
8.
9.public class BusinessService {
10.
11. public static void main(String[] args) {
12.
13. Configuration config = new Configuration().configure();
14. SessionFactory sessionFactory = config.buildSessionFactory();
15. Session session = sessionFactory.openSession();
16.
17. User user1 = (User) session.load(User.class, new Integer(1));
18. User user2 = (User) session.load(User.class, new Integer(1));
19. System.out.println(user1 == user2);
20.
21. user1 = (User) session.load(User.class, new Integer(1));
22. session.evict(user1);
23. user2 = (User) session.load(User.class, new Integer(1));
24. System.out.println(user1 == user2);
25.
26. user1 = (User) session.load(User.class, new Integer(1));
27. session.clear();
28. user2 = (User) session.load(User.class, new Integer(1));
29. System.out.println(user1 == user2);
30.
31. Session session1 = sessionFactory.openSession();
32. user1 = (User) session1.load(User.class, new Integer(1));
33. session1.close();
34. Session session2 = sessionFactory.openSession();
35. user2 = (User)session2.load(User.class, new Integer(1));
36. session2.close();
37. System.out.println(user1 == user2);
38.
39. session.close();
40. sessionFactory.close();
41. }
42.}
依次打印出的結果為
true
false
false
false
可見:
使用session.evict或者session.clear把某個物體從緩存中移除,或者直接關閉Session,都會使緩存失效,或者說釋放緩存占用的資源空間。
值得一提的是:在載入大量數據時,應該及時手動清除一級緩存以釋放資源。
例如:
1.Session session = sessionFactory.openSession();
2.Transaction tx = session.beginTransaction();
3.
4.while(....) { // 大量載入物件時的迴圈示意
5. ....
6. session.save(someObject);
7. if(count % 100 == 0) { // 每100筆資料
8. session.flush(); // 送入資料庫
9. session.clear(); // 清除快取 10. }
11.}
12.
13.tx.commit();
14.session.close();
在SQL Server、Oracle等數據庫可使用hibernate的配置文件進行配置,如:
1.....
2.<hibernate-configuration>
3. <session-factory>
4. ....
5. <property name="hibernate.jdbc.batch_size">100</property>
6. ....
7. </session-factory>
8.<hibernate-configuration>
注意:在MySQL中不支持這種配置方式。