修改BusinessService.java文件如下所示:
- package com.hb3.pack_01;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- import com.hb3.pack_01.model.User;
- public class BusinessService {
- public static void main(String[] args) {
-
- Configuration config = new Configuration().configure();
- SessionFactory sessionFactory = config.buildSessionFactory();
- Session session = sessionFactory.openSession();
-
- User user1 = (User) session.load(User.class, new Integer(1));
- User user2 = (User) session.load(User.class, new Integer(1));
- System.out.println(user1 == user2);
-
- user1 = (User) session.load(User.class, new Integer(1));
- session.evict(user1);
- user2 = (User) session.load(User.class, new Integer(1));
- System.out.println(user1 == user2);
- user1 = (User) session.load(User.class, new Integer(1));
- session.clear();
- user2 = (User) session.load(User.class, new Integer(1));
- System.out.println(user1 == user2);
-
- Session session1 = sessionFactory.openSession();
- user1 = (User) session1.load(User.class, new Integer(1));
- session1.close();
- Session session2 = sessionFactory.openSession();
- user2 = (User)session2.load(User.class, new Integer(1));
- session2.close();
- System.out.println(user1 == user2);
-
- session.close();
- sessionFactory.close();
- }
- }
依次打印出的结果为
true
false
false
false
可见:
使用session.evict或者session.clear把某个物体从缓存中移除,或者直接关闭Session,都会使缓存失效,或者说释放缓存占用的资源空间。
值得一提的是:在载入大量数据时,应该及时手动清除一级缓存以释放资源。
例如:
- Session session = sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- while(....) { // 大量載入物件時的迴圈示意
- ....
- session.save(someObject);
- if(count % 100 == 0) { // 每100筆資料
- session.flush(); // 送入資料庫
- session.clear(); // 清除快取
- }
- }
- tx.commit();
- session.close();
在SQL Server、Oracle等数据库可使用hibernate的配置文件进行配置,如:
- ....
- <hibernate-configuration>
- <session-factory>
- ....
- <property name="hibernate.jdbc.batch_size">100</property>
- ....
- </session-factory>
- <hibernate-configuration>
注意:在MySQL中不支持这种配置方式。
ExtJS教程-
Hibernate教程-
Struts2 教程-
Lucene教程