这是我使用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();
我的应用程序大部分时间都能正常工作,但有时当我向数据库添加一个对象并执行查询时,新添加的对象不会返回。我猜连接已被缓存返回旧结果。我的配置有问题吗?
答案 0 :(得分:0)
我可能是您正在使用交易并正在重复使用它们。如果是这种情况,您应该为您所做的每件事开始新的交易。
例如:https://stackoverflow.com/a/24197494/3959856
您可能还想使用
session.flush();
session.commit();
添加和删除后。