【Hibernate】一级、二级缓冲
ok,什么是缓冲?
一级缓冲
@Test
publicvoid findTestyijihuanchong(){
Session s=sessionFactory.openSession();
s.beginTransaction();
Person person=(Person)s.load(Person.class, 1);
System.out.println(person.getName());
//因为Session存在缓冲,所以这个查询直接在session中取
Person person2=(Person)s.load(Person.class, 1);
System.out.println(person2.getName());
s.getTransaction().commit();
}
@Test
publicvoidfindTestyijihuanchong(){
Sessions=sessionFactory.openSession();
s.beginTransaction();
Personperson=(Person)s.load(Person.class, 1);
System.out.println(person.getName());
s.getTransaction().commit();
s.close();
Sessions2=sessionFactory.openSession();
s2.beginTransaction();
Personperson2=(Person)s2.load(Person.class, 1);
System.out.println(person2.getName());
s2.getTransaction().commit();
s2.close();
}
二级缓冲
<!-- 开启缓冲 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!--指定是哪个二级缓冲-->
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<!-- 使用查询二级缓冲 -->
<propertyname="hibernate.cache.use_query_cache">true</property>
@Entity
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
@Table(name="p_person")
XML配置
<class name="Person" table="t_person">
<cache usage="read-write"/>
<id name="id">
@Test
publicvoid findTesterjihuanchong(){
Sessions=sessionFactory.openSession();
s.beginTransaction();
Personperson=(Person)s.load(Person.class, 1);
System.out.println(person.getName());
s.getTransaction().commit();
s.close();
Sessions2=sessionFactory.openSession();
s2.beginTransaction();
Personperson2=(Person)s2.load(Person.class, 1);
System.out.println(person2.getName());
s2.getTransaction().commit();
s2.close();
}
查询缓冲
ok,看代码
@Test
publicvoid findTestList(){
Sessions=sessionFactory.getCurrentSession();
s.beginTransaction();
List<Person>persons=s.createQuery("fromPerson").setCacheable(true).list();
List<Person>person1=s.createQuery("fromPerson").setCacheable(true).list();
for(Person person:persons){
System.out.println(person.getName()+"----"+person.getId());
}
for(Person person:person1){
System.out.println(person.getName()+"----"+person.getId());
}
s.getTransaction().commit();
}