0
votes

I tried first time to use second level cache according different tutorials and it doesn't work. I have class :

@Entity
@Table(name="TABLE_NAME")
@org.hibernate.annotations.Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
public class Foo {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;


@OneToMany(mappedBy = "foo", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Sentence> collection_name;

and configuration in my hibernate.cfg.xml file

 <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
 <property name="hibernate.cache.use_second_level_cache">true</property>
 <property name="hibernate.cache.use_query_cache">true</property>

I turned on

<property name="show_sql">true</property>

I thought that second query won't hit database, but it does.

my Query :

  List<Foo> result = session.createQuery("select p from Foo p order by size(p.collection_name) desc ").list();

What is wrong ?

2

2 Answers

0
votes

If you want to cache your HQL quert result, you have to instrument your query:

List<Foo> result = session
                      .createQuery("select p from Foo p order ... ")
                      .setCacheable(true)
                      .list();

Additionaly you can tell Hibernate, which cache configuration (cache region) it should use:

List<Foo> result = session
                      .createQuery("select p from Foo p order ... ")
                      .setCacheable(true)
                      .setCacheRegion("foo_region")
                      .list();

Of course, global setting hibernate.cache.use_query_cache must be set to true.

@Cache annotation on entity class is used to cache single entity when it is fetched by ID:

Foo foo = session.get(Foo.class, fooId);
0
votes

In both the foo.java and Sentence.java specify @Cacheable ``@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)

Also just after the @OneToMany annotation specify ``@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)

if you are using Query object: Query q enable the cacheable to true