- get/load区别 如果记录存在,get返回对象(或代理对象);否则返回null。 如果记录存在,load返回对象;否则返回 NotObjectFoundException 2.hibernate Cache 2.1 一级缓存,在当前session内 2.2 Query Cache Cache queries and results. 方法: 1. 在hiberante Configuration 文件中: true 2. 查询时 Query query = session.createQuery("from Person p where p.id=1"); query.setCacheable(true); 2.3 二级缓存, 跨session . 如EHCache 3. load 与 CreateQuery 在处理Cache的区别 首先,load时在一个session中,一级缓存总是有效的。比如下面的只issue sql操作一次 Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Person person1 = (Person) session.load(Person.class, 1L);
System.out.println(person1.getFirstName());
Person person2 = (Person) session.load(Person.class, 1L);
System.out.println(person2.getFirstName());
tx.commit();
session.close(); 其次,如果用CreateQuery有点不同,比若下面的需要issue sql操作两次 Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("from Person p where p.id=1");
Iterator it = query.list().iterator();
while (it.hasNext ()){
Person p = (Person) it.next();
System.out.println(p.getFirstName());
}
query = session.createQuery("from Person p where p.id=1");
it = query.list().iterator();
while (it.hasNext ()){
Person p = (Person) it.next();
System.out.println(p.getFirstName());
}
tx.commit();
session.close(); 原因是session cache时是根据key(load方法中传入的ID)来缓存的。解决的方法是: 1. 用load,如上面的代码 2. 用查询缓存,如上面的介绍 Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("from Person p where p.id=1");
query.setCacheable(true);
Iterator it = query.list().iterator();
while (it.hasNext ()){
Person p = (Person) it.next();
System.out.println(p.getFirstName());
}
query = session.createQuery("from Person p where p.id=1");
query.setCacheable(true);
it = query.list().iterator();
while (it.hasNext ()){
Person p = (Person) it.next();
System.out.println(p.getFirstName());
}
tx.commit();
session.close();