Hibernate Cache
If a record exists, get returns the object (or proxy object); Otherwise, return null. If the record exists, load returns the object; Otherwise, return NotObject FoundException 2. Hibernate Cache 2.1 Level 1 Cache, 2.2 Query Cache Cache queries and results in the current session. Method: 1 In the hibernate Configuration file:
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(); Secondly, if using CreateQuery is a bit different, it requires two issue SQL operations compared to the one below 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(); The reason is that session caching is cached based on the key (ID passed in the load method). The solution is: 1 Use load, as in code 2 above Using query caching, as introduced above, 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();