用例子理解hibernate的一級快取
阿新 • • 發佈:2019-01-08
//Open the hibernate session Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Session sessionTemp = HibernateUtil.getSessionFactory().openSession(); sessionTemp.beginTransaction(); try { //fetch the department entity from database first time DepartmentEntity department = (DepartmentEntity) session.load(DepartmentEntity.class, new Integer(1)); System.out.println(department.getName()); //fetch the department entity again department = (DepartmentEntity) session.load(DepartmentEntity.class, new Integer(1)); System.out.println(department.getName()); department = (DepartmentEntity) sessionTemp.load(DepartmentEntity.class, new Integer(1)); System.out.println(department.getName()); } finally { session.getTransaction().commit(); HibernateUtil.shutdown(); sessionTemp.getTransaction().commit(); HibernateUtil.shutdown(); } Output: Hibernate: select department0_.ID as ID0_0_, department0_.NAME as NAME0_0_ from DEPARTMENT department0_ where department0_.ID=? Human Resource Human Resource Hibernate: select department0_.ID as ID0_0_, department0_.NAME as NAME0_0_ from DEPARTMENT department0_ where department0_.ID=? Human Resource
你可以看到,儘管實體已經存在於Session物件中了,但是當使用另一個Session物件sessionTemp的時候依舊會執行資料庫查詢語句。