hibernate 状态

来源:互联网 发布:spss软件18.0安装 编辑:程序博客网 时间:2024/05/19 02:16

flush and clear

* * flush: 进行清理缓存(此时缓存中的数据并不丢失)的操作,让缓存和数据库同步 执行一些列sql语句,但不提交事务,;   commit:先调用flush() 方法,然后提交事务. 则意味着提交事务意味着对数据库操作永久保存下来。   reresh:刷新,让session和数据库同步,执行查询,把数据库的最新信息显示出来,更新本地缓存的对象状态.   clear:清空缓存,等价于list.removeAll(); */public class FlushAndClear {private static SessionFactory sf;static{Configuration config=new Configuration();config.configure("cn/itcast/hibernate/state/hibernate.cfg.xml");config.addClass(Customer.class);config.addClass(Order.class);sf=config.buildSessionFactory();}//测试flush和clear@Testpublic void findCustomer(){Session s=sf.openSession();Transaction ts=s.beginTransaction();//查询2号客户Customer c2=(Customer)s.get(Customer.class,2);//产生select//清理缓存 方向:从缓存到数据库  让缓存中的数据和数据库中的数据同步//把缓存中的数据写到数据库中 还未commit//注意:清理缓存中的数据不消失s.flush();//不会产生select session的一级缓存中有  所以不会产生select语句 Customer c1=(Customer)s.get(Customer.class,2);/** * 清空缓存 相当于list.removeAll(); */s.clear();//有select语句Customer c3=(Customer)s.get(Customer.class,2);}//测试refresh@Testpublic void testRefresh(){Session s=sf.openSession();Transaction ts=s.beginTransaction();Customer c=(Customer)s.get(Customer.class,1);c.setName("三");/** * 让缓存区的数据和数据库中的数据库同步 方向:从数据库到缓存  不会产生update */s.refresh(c);ts.commit();s.close();}//清理session的缓存(设置缓存的清理模式 )@Testpublic void testFlush(){Session s=sf.openSession();//设置缓存清理模式s.setFlushMode(FlushMode.NEVER);Transaction ts=s.beginTransaction();Customer c=new Customer();c.setName("xxxxx");s.save(c);/** * 当缓存清理模式设置为 FlushMode。NEVER时 * Session的查询方法 不清理  ts的commit()不清理 * Session的flush()清理 * 所以必须要加上s.flush才能加入数据 */s.flush();ts.commit();s.close();}//批量处理@Testpublic void testBatchInsert(){Session s=sf.openSession();s.setFlushMode(FlushMode.NEVER);Transaction ts=s.beginTransaction();for(int i=0;i<1050;i++){Customer c=new Customer();c.setName("liu"+i);s.save(c);if(i%100==0){s.flush();s.clear();}}s.flush();ts.commit();s.clear();}}