Code:
@Entity
@Table
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY, region = "Account_region")
public class Account
{
@Id
private int accId;
@Column
private String name;
}
hibernate-cfg.xmlCode:
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- optional -->
<property name="hibernate.generate_statistics">true</property>
Code:
Test.java
{
private static void printStats(Statistics stats, int i)
{
logger.info("***** " + i + " *****");
logger.info("Fetch Count=" + stats.getEntityFetchCount());
logger.info("Second Level Hit Count=" + stats.getSecondLevelCacheHitCount());
logger.info("Second Level Miss Count=" + stats.getSecondLevelCacheMissCount());
logger.info("Second Level Put Count=" + stats.getSecondLevelCachePutCount());
}
private void createAccount(int id)
{
Account acc = new Account();
acc.setAccId(id);
acc.setName("Finance");
session.save(acc);
logger.info("Account succesfully created.");
}
private void fetchAccount(int id)
{
try
{
logger.info("Before fetching acc with id : {}", id);
printStats(stats, i++);
Criteria criteria = session.createCriteria(Account.class);
criteria.add(Restrictions.idEq(id));
criteria.setCacheable(true);
System.out.println(criteria.list());
logger.info("After fetching acc with id : {}", id);
printStats(stats, i++);
}
catch(Exception e)
{
e.printStackTrace();
}
}
@Test
public void test1()
{
logger.info("Initial statistics.");
printStats(stats, i++);
int id = 1;
createAccount(id);
fetchAccount(id);
[color=#FF0000]fetchAccount(id);[/color]
}
}
When the marked line is executing, why it is firing the query again though that query has already been cached?