hibernate学习6_session之clear与flush
1、session的clear()方法
hibernate从数据库中get或load记录时,或先去session一级缓存中查找对应数据,如果缓存中没有记录,则去对应数据库中查询,
如果有记录则直接从缓存中获取。
public void testClear() { Session session1 = sf.getCurrentSession(); session1.beginTransaction(); Student t1 = (Student) session1.get(Student.class, 45); //session1.clear(); Student t2 = (Student) session1.get(Student.class, 45); session1.getTransaction().commit(); }
执行时只会发出一次查询
Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from Student student0_ where student0_.id=?
加上session的clear()方法后,会清空当前session缓存,数据库查询两次,如下:
Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from Student student0_ where student0_.id=?
Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from Student student0_ where student0_.id=?
2、session的flush方法
flush方法会强制同步当前session缓存数据至数据库中,如下:
@Test public void testFlush() { Session session1 = sf.getCurrentSession(); session1.beginTransaction(); Student t1 = (Student) session1.get(Student.class, 45); t1.setAge(30); t1.setAge(40); session1.getTransaction().commit(); }
此时数据库中load出对应记录后,虽然前后连续更改了两次属性,数据库只执行一次update
Hibernate: update Student set age=?, name=? where id=?
加上flush后:
public void testFlush() { Session session1 = sf.getCurrentSession(); session1.beginTransaction(); Student t1 = (Student) session1.get(Student.class, 45); t1.setAge(30); session1.flush(); t1.setAge(40); session1.getTransaction().commit(); }
数据库连续执行两次update
Hibernate: update Student set age=?, name=? where id=?
Hibernate: update Student set age=?, name=? where id=?