gpt4 book ai didi

java - HibernateSessionFactory 类不会更改数据库中的数据

转载 作者:行者123 更新时间:2023-11-30 01:13:27 24 4
gpt4 key购买 nike

在我们的应用程序中,我们有一个 HibernateSessionFactory 类,用于打开和关闭连接。一切都很好,但是当我们更新数据库中的数据时,它在我们的应用程序中并没有改变。不幸的是,我们从数据库中看到了旧数据。我该如何解决这个问题?

public class HibernateSessionFactory {

private static final ThreadLocal threadLocal = new ThreadLocal();
private static org.hibernate.SessionFactory sessionFactory;

private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry;

private static final Logger log = Logger.getLogger(
HibernateSessionFactory.class);

static {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
log.error("Error Creating SessionFactory", e);
}
}

private HibernateSessionFactory() {}

public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ?
sessionFactory.openSession() : null;

threadLocal.set(session);
}
return session;
}

public static void rebuildSessionFactory() {

try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
log.error("Error Creating SessionFactory", e);
}
}

public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.flush();
session.close();

}
}

public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}

public static Configuration getConfiguration() {
return configuration;
}

}

.

@SuppressWarnings("unchecked")
public List<Tauthor> getAuthors() throws HibernateException {
log.debug("getting all authors");
Query queryObject = null;
List<Tauthor> authors = null;
Session session = HibernateSessionFactory.getSession();
try {
String queryString = "from Tauthor";
queryObject = session.createQuery(queryString);
authors = queryObject.list();
} catch (HibernateException e) {
log.error("get all authors failed", e);
throw e;
} finally {
HibernateSessionFactory.closeSession();
}
return authors;
}

最佳答案

您尚未共享将数据写入数据库的代码。如果没有这个,我只能想到为什么您的数据输出是旧数据而不是新数据的几个原因:

  1. 您的交易尚未提交。
  2. 在您查询数据时,Hibernate 尚未写入数据库。
  3. Hibernate 的缓存尚未更新,这导致查询返回旧数据。

您应该使用数据库开发工具验证数据是否已写入数据库,并尝试禁用所有 hibernate 缓存以查看结果是否发生变化。

关于java - HibernateSessionFactory 类不会更改数据库中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19277121/

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