views:

74

answers:

1

I'm benchmarking the performance gains from using a 2nd level cache in Hibernate (enabling EhCache), but it doesn't seem to improve performance. In fact, the time to perform the query slightly increases.

The query is:

session.createCriteria(MyEntity.class).list();

The entity is:

@Entity
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class MyEntity {
    @Id
    @GeneratedValue
    private long id;

    @Column(length=5000)
    private String data;

    //---SNIP getters and setters---
}

My hibernate.cfg.xml is:

<!-- all the normal stuff to get it to connect & map the entities plus:-->
<property name="hibernate.cache.region.factory_class">
    net.sf.ehcache.hibernate.EhCacheRegionFactory
</property>

The MyEntity table contains about 2000 rows.

The problem is that before adding in the cache, the query above to list all entities took an average of 65 ms. After the cache, they take an average of 74 ms. Is there something I'm missing? Is there something extra that needs to be done that will increase performance?

A: 

By default, the results of queries are not cached, only the entities are cached. So every time you run your query, SQL is still being issued, which returns the IDs of the entities matching the query. Those entities are then retrieved from the cache (if present).

If you want query results to be cached, you need to turn that on explicitly.

skaffman
Thanks, I enabled the query cache and it definitely makes a difference. The query went from 65 ms uncached to 22 ms after it's warmed up.
James Smith
@James: The difference should be more noticeable with a more complex query.
skaffman