【发布时间】:2015-12-05 21:11:17
【问题描述】:
我刚刚经历了this article 和this,我发现它们可以提高我的应用程序的性能,因为它只有 99% 的读取操作。我首先在测试应用程序中实现它只是为了测试它(参考this),虽然我得到了结果,但根据我提到的第二个链接,如果查询对于 same 参数值是相同的, 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'。我的意思是应该用 where 参数作为键 命中 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=?
Test1:UserDetails [userName=ak416, password=magnum16, name=Borat16, msisdn=116]
【问题讨论】:
标签: java spring hibernate postgresql