gpt4 book ai didi

java - Hibernate 查询缓存,行为不符合预期

转载 作者:行者123 更新时间:2023-11-29 14:19:33 25 4
gpt4 key购买 nike

我刚刚浏览了 this articlethis我发现这将提高我的应用程序的性能,因为它只有 99% 的读取操作。我首先在测试应用程序中实现它只是为了测试它(引用 this ),虽然我得到了结果但是根据我提到的第二个链接,如果查询对于 same 参数值相同,数据库命中将发生,但基于关系的主键

类如下:

实体类

@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>

//第一个查询结果:根据文章,第一次会命中数据库(如预期的那样)

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 parameter as key 命中数据库。我缺少什么?!

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]

最佳答案

你正在使用

<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

所以你的缓存没有启用(NoCacheProvider)

关于java - Hibernate 查询缓存,行为不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34110952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com