這裏是我的數據庫配置連接使用Hibernate到DB:數據庫連接不更新
public class HibernateUtil {
public static HibernateUtil mInstance = null;
public static HibernateUtil getInstance(DBMode dbMode) {
if (mInstance == null) {
mInstance = new HibernateUtil(dbMode);
}
return mInstance;
}
private SessionFactory sessionFactory;
private HibernateUtil(DBMode dbMode) {
buildSessionFactoryTest();
}
private void buildSessionFactoryTest() {
Configuration configuration = new Configuration()
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
.setProperty("hibernate.connection.url",
"jdbc:mysql://ip:port/DB?createDatabaseIfNotExist=true&autoReconnect=true&useUnicode=true&connectionCollation=utf8_general_ci&characterSetResults=utf8&characterEncoding=utf-8")
.setProperty("hibernate.connection.username", "root")
.setProperty("hibernate.connection.password", "password")
.setProperty("hibernate.hbm2ddl.auto", "update").setProperty("c3p0.max_size", "20")
.setProperty("c3p0.timeout", "1800").setProperty("3p0.min_size", "5")
.setProperty("hibernate.c3p0.max_statements", "0")
.setProperty("connection.provider_class", "org.hibernate.connection.C3P0ConnectionProvider")
.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
public Session getSession() {
Session session;
try {
session = sessionFactory.getCurrentSession();
} catch (HibernateException e) {
session = sessionFactory.openSession();
}
if (session == null || sessionFactory.isClosed() || !session.isConnected() || !session.isOpen()) {
sessionFactory.close();
buildSessionFactoryTest();
session = sessionFactory.openSession();
}
return session;
}
}
,這裏是我是如何從HibernateUtil的獲取會話:
Session session = HibernateUtil.getInstance(dbMode).getSession();
我的應用程序大部分時間都能正常工作,但有時當我向數據庫添加一個對象並執行查詢時,新添加的對象不會返回。我猜連接已被緩存返回舊的結果。我的配置有問題嗎?
像Session.get(Class,int)這樣的一些API將總是進入數據庫(而不是獲取緩存的數據)。我建議你閱讀一些Hibernate教程。 –
@dsp_user我想去數據庫的每個請求新的連接是昂貴的時間複雜性,因爲我部署後運行數據庫的第一次連接運行總是緩慢。 – Narges
我不是在談論爲每個數據庫操作創建一個新的數據庫連接。當然,你應該重用你的db連接。我只是說一些Hibernate API會一直到數據庫,並因此獲取最新的數據/更新。 –