我刚刚浏览了this article和this,我发现它会提高应用程序的性能,因为它只有99%的读取操作。我首先在测试应用程序中实现它只是为了测试它(引用this),虽然我得到了结果但是根据我提到的第二个链接,如果查询对于相同参数是相同的值,db命中率将基于主键的关系。
课程如下:
实体类
@Entity(name="User_Details")
public class UserDetails {
@Id
private String userName;
private String password;
private String name;
private Long msisdn;
//getter and setter are in place//
}
DAO课程
public class UserDetailsDAOImpl {
SessionFactory sessionFactory;
public UserDetailsDAOImpl() {
sessionFactory = new Configuration().configure().buildSessionFactory();
}
public UserDetails getUser(String param1) {
Session session = sessionFactory.openSession();
System.out.println("session : " + session);
session.beginTransaction();
Criteria query = session.createCriteria(UserDetails.class).add(Restrictions.eq("name",param1));
UserDetails dummy_user=(UserDetails) query.setCacheable(true).uniqueResult();
session.close();
return dummy_user;
}
主要类
UserDetailsDAOImpl obj=new UserDetailsDAOImpl();
UserDetails response = obj.getUser("Borat16");
System.out.println("Test:"+response);
UserDetails response1 = obj.getUser("Borat16");
System.out.println("Test1:"+response1);
hibernate.cfg.xml中
<property name="hibernate.cache.use_second_level_cache">true</property>
<!--<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>-->
<property name = "hibernate.cache.use_query_cache">org.hibernate.cache.EhCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
// 第一个查询结果:根据文章的第一次,它会点击db(如预期的那样)
Hibernate: select this_.userName as userName1_0_0_, this_.msisdn as msisdn2_0_0_, this_.name as name3_0_0_, this_.password as password4_0_0_ from User_Details this_ where this_.name=?
Test:UserDetails [userName=ak416, password=magnum16, name=Borat16, msisdn=116]
// 第二个查询结果:现在由于查询相同且相同的参数,为什么生成的sql语句看起来不像“select * from user_details where userName ='ak47'。我的意思是它应该使用以参数为键命中数据库。我缺少什么?!
Hibernate: select this_.userName as userName1_0_0_, this_.msisdn as msisdn2_0_0_, this_.name as name3_0_0_, this_.password as password4_0_0_ from User_Details this_ where this_.name=?
Test1:UserDetails [userName=ak416, password=magnum16, name=Borat16, msisdn=116]
答案 0 :(得分:2)
您正在使用
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
因此您的缓存未启用( NoCacheProvider )
答案 1 :(得分:1)
一旦设置了cache_provider值,请确保将以下值设置为&#34; true&#34;启用查询级缓存。
<property name="hibernate.cache.use_query_cache">true</property>