Caching best practices

Vlad Mihalcea


There is an irresistible attraction to writing custom caching solutions, since it seems to be the easiest path to “improving” the overall application performance. Well, caching is a great technique, but there are few steps to consider before even considering it.

Best practices

  1. A key/value collection is not a Cache

    Almost all projects I worked on have been using some sort of custom caching solutions, built on top of Java Maps. A Map is not an out-of-the-box Caching solution, since a Cache is more than a key/value store. A Cache also requires:

    • eviction policies
    • max size limit
    • persistent store
    • weak references keys
    • statistics

    A Java Map doesn’t offer these features and you shouldn’t spend your customer’s money to write a custom cache solution either. You should choose a professional cache like EHCache or Guava Cache, which are both powerful and simple to use. Those tools are constantly tested…

View original post 476 more words


Hibernate Facts: Multi level fetching

Vlad Mihalcea

It’s quite common to retrieve a root entity along with its children associations on multiple levels.

In our example we need to load a Forest with its Trees and Branches and Leaves, and we will try to see have Hibernate behaves for three collection types: Sets, Indexed Lists, and Bags.

This is how our class hierarchy looks like:


Using Sets and Indexed Lists is straight forward since we can load all entities by running the following JPA-QL query:

and the executed SQL query is:

But when our children associations are mapped as Bags, the same JPS-QL query throws a “org.hibernate.loader.MultipleBagFetchException”.

In case you can’t alter your mappings (replacing the Bags with Sets or Indexed Lists) you might be tempted to try the something like:

But this is inefficient generating a plethora of SQL queries:

So, my solution is to simply get the lowest level children and fetch all needed associations…

View original post 281 more words