I am using Hibernate 4.3.11
I have configured 2nd level cache for my Song class, but not getting many hits and I wonder if its because I usually retrieve my Song Class as follows.
public static List<Song> getSongsFromDatabase(Session session, List<Integer> ids)
{
try
{
List<Song> songs = session
.createCriteria(Song.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.add(Restrictions.in("recNo", ids)).list();
return songs;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
This is just retrieving by primary key, but do I have do it a different way for Ehcache to be used ?
I think its only working when I use the lookup one Id method
public static Song getSongFromDatabase(Session session, Integer id)
{
try
{
return (Song) session.get(Song.class, id);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
It all depends how your 2nd level cache is configured.
If an entity is annotated @Cache
, indeed, it will get cached during a session.get
.
For a query, you need to make it cacheable. Which means in your case to do something like this:
List<Song> songs = session
.createCriteria(Song.class)
.setCacheable(true) // here
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.add(Restrictions.in("recNo", ids)).list();