One of our developers came up with some sample code like the following:

//create an entity

Entity e = new Entity();

e.setEntityName(“x”);

EntityId id = dao.create(e);

//attempt to find it

Entity e2 = dao.createQuery(“from Entity where entityName=’x’).list.get(0);

//???? e2 is null !!!!!!

//look a different way

Entity e3 = dao.findById(id);

//???? e3 is correctly loaded

The Hibernate cache is id based. So, HQL queries ignore the cache when looking around for matches and go direct to the db (e2), unless id’s are involved (e3).

The choices are then:

– If you need to reference cache objects by other than id (as above), keep a map as you progress

HashMap<String,EntityId> map.put(“x”,id);

Entity e4 = dao.findById(map.get(“x”));

– or flush() as needed so the HQL will ‘work’

I think most of the time this (keeping id’s around) works. For example most DTOs and UI representations are maintaining the id of the object and later retrieving by that id. Unfortunately, I know there are a couple of pain points where the id is not the key of interest so additional coding will have to be used.

Also, flushing continually defeats the whole purpose of having a long running session/transaction.  So, that option is of limited use as well.