下面是我使用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();
我的应用程序大多数时候都正常工作,但有时当我向数据库添加一个对象并执行查询时,新添加的对象不会返回。我猜连接已被缓存并返回旧结果。我的配置有问题吗?
1条答案
按热度按时间pepwfjgg1#
我可能认为您正在使用事务并正在重用它们。如果是这样的话,你应该为你做的每件事开始一个新的事务。
例如:https://stackoverflow.com/a/24197494/3959856
您可能还想使用
添加和删除后。