I’m using Hibernate with its L1 (Session) cache only. I was wondering whether it could be possible to pre-populate it.
Suppose I have an Item table, where each item has its own id, and I need to issue queries like “from Item where id = :id“: if I could pre-load all the items at once I could have quicker response time (I’m using Hibernate from a Servlet under Tomcat).
Yes, that’s possible. You’ll execute your select once (without where condition and without using the resulting list), and then the data are in the session’s first level cache until you clear the session or throw it away.
But in that case you have no control if the session itself throws away the pre-loaded data from its cache (this is not a functional problem, only a performance problem, and I have the feeling the hibernate version which I’m using never does so). If you want to have full control, you store the preloaded data in a static variable (a List or Map instance) and write a service which reads from this static variable instead from the database. By the way, in your environment the access to this static variable must be synchronised.