The configuration of caching is provided by the Hibernate documentation.
public class
Employee {
private Employee manager;
private String forename;
private String surname;
private Set<Employee> staff;
//setters and getters
}
|
Conceptual Employee Data Cache
Id [forename, surname, manager,
[staff] ]
1 [ “John”, “Smith”, null, [2, 3] ]
2 [“Sarah”,”Brown”, 1, [] ]
3 [“Gavin”, “Adams” 1, [] ]
|
So if the Employee with id 1 is queried from the database without the cache, it would result in the following queries:
select * from Employee where
id=1 ; load the employee with id 1
select * from Employee where manager_id=1
; load the staff of 1 (will return 2, 3)
select * from Employee where manager_id=2
; load any potential staff of 2 (will return none)
select * from Employee where manager_id=3
; load any potential staff of 3 (will return none)
|
With the cache enabled, there would be no SQL select statements executed. If however, the associations were not cached then it would result in all the queries except the first. Therefore, it is best to cache associations whenever possible.
The above queries were based on using the entity identifier. If the query were more complex such as by forename then Hibernate must still issue a select statement to retrieve the identifier of the entity before the cache can be queried for associations.
//Complex query
Query query = session.createQuery("from Employee as e where e.forename=?"); query.setString(0, "John"); List l = query.list();
//single SQL select statment to retrieve id.
select * from Employee where forename='John'
|