Does Hibernate cache the results get from Session.list()? What my believe is session.get() or session.load() method cache the result in the memory but session.list() doesn't as it generate lots of record that might cause memory issue but in case of get and load it will only generate single object.
1 Answers
Actually it does generate memory issues if you are not careful.
But you will hit another limit before: performance...
Everything Hibernate loads inside a transaction is stored in the context. Every time you try to load an object, it checks in the context first if it doesn't already exist. Having a lots of entities stored in the context is a huge performance hit (for complex reasons I won't detail here).
If Hibernate didn't do this, it would return many instances of the same entity, with duplicated data. If you updated them, it wouldn't be able to know which data to persist to database.
Rule of the thumb: Keep your transactions short, or evict()
the entities from the context as soon as possible if you don't need them anymore.
PS: It is not called "cache"; the session is a context necessary to perform its ORM tasks correctly. There are second-level cache libraries, but it's a totally different thing.

- 5,905
- 2
- 31
- 59
-
Thanks Guillaume. actually i am referring to first level cache. now can you please explain me in terms of Caching to return object from db. – Rohit Apr 01 '17 at 05:16
-
Yes, this "first level cache" is called "context" to avoid confusion with a simple cache. The context does a lot more things. What do you want to know when you say "Caching to return object from db" ? I don't get the question. – Guillaume F. Apr 01 '17 at 05:31