gpt4 book ai didi

java - hibernate 数据获取

转载 作者:行者123 更新时间:2023-11-29 04:52:39 24 4
gpt4 key购买 nike

这是我获取数据的方式:

public static List<SubjectSubjectUsersUsers> getAllSubjectUsers()
{
List<SubjectSubjectUsersUsers> theList = null;

Session session = ServiceLocator.getSessionFactory().openSession();

try{

theList = session.createSQLQuery("SELECT s.name as subject_name, u.name as user_name, u.surname as user_surname, su.id as id from subjects s "
+ "join subject_users su on s.id = su.subject_id join users u on su.user_id = u.id")

.addScalar("subject_name", StandardBasicTypes.STRING)
.addScalar("user_name", StandardBasicTypes.STRING)
.addScalar("user_surname", StandardBasicTypes.STRING)
.addScalar("id", StandardBasicTypes.LONG)
.setResultTransformer(Transformers.aliasToBean(SubjectSubjectUsersUsers.class)).list();


}catch(Exception e){

e.printStackTrace();

}finally{

session.flush();
session.close();

}


return theList;
}

问题是当我在数据库中手动更新数据时,获取的数据没有改变。但是当我重新加载服务器和 IDE 时,它就可以工作了。问题的原因可能是什么?我想我以不正确的方式使用了 session 对象。谢谢。

最佳答案

你需要设置CacheMode刷新

query.setCacheMode(CacheMode.REFRESH);

您的查询将类似于 -

theList = session.createSQLQuery("SELECT s.name as subject_name, u.name as user_name, u.surname as user_surname, su.id as id from subjects s "
+ "join subject_users su on s.id = su.subject_id join users u on su.user_id = u.id")

.setCacheMode(CacheMode.REFRESH)
.addScalar("subject_name", StandardBasicTypes.STRING)
.addScalar("user_name", StandardBasicTypes.STRING)
.addScalar("user_surname", StandardBasicTypes.STRING)
.addScalar("id", StandardBasicTypes.LONG)
.setResultTransformer(Transformers.aliasToBean(SubjectSubjectUsersUsers.class)).list();

但是,在使用 hibernate 时从外部更新 DB 是个坏主意,否则您将无法获得 hibernate 缓存的好处。

关于java - hibernate 数据获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34840029/

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