【发布时间】:2011-01-04 10:38:32
【问题描述】:
我有以下代码:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
Configuration cfg = new Configuration();
cfg=cfg.configure();
sessionFactory = cfg.buildSessionFactory();
} catch (Throwable ex) {
System.out.println("** Initial SessionFactory creation failed: " + ex.getMessage());
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal hibernateSession = new ThreadLocal();
public static Session currentSession() {
Session s = (Session) hibernateSession.get();
if (s == null) {
s = sessionFactory.openSession();
//System.out.println("sessionFactory.openSession()");
hibernateSession.set(s);
}
return s;
}
public static void closeSession() {
Session s = (Session) hibernateSession.get();
if (s != null)
s.close();
hibernateSession.set(null);
}
}
还有
public class Db {
public static synchronized void Insert(Object updateBean) {
org.hibernate.Session hibernateSession = HibernateUtil.currentSession();
try {
Transaction tx = hibernateSession.beginTransaction();
hibernateSession.save(updateBean);
tx.commit();
} catch(Exception e) {
System.out.println("*hibernate insert Exception: "+e.getMessage());
}
HibernateUtil.closeSession();
}
}
Hibernate 正在使用 c3p0 池化。 然后在繁忙的服务器生产环境中从 JSP 页面调用 Db.Insert。
我的问题是,如果我删除了 Db.Insert(Object) 上的“同步”,这会导致问题吗?
我意识到这是我很可能已经知道的事情,但不要也不想尝试它并得到错误。
另外,如果它可能导致上述问题,那么我不确定我是否理解使用 c3p0 进行连接池的意义......我目前的理解是调用 HibernateUtil.currentSession();或 hibernateSession.beginTransaction();从 c3p0 池中调用一个可用的连接,并且永远不会相遇。
抱歉,第一个代码没有显示“代码”,这个网络表单只是不想正常工作。
感谢阅读
【问题讨论】:
-
我为您格式化了代码 - 下次请使用编辑器中的
{}按钮,或者简单地将您的代码缩进 4 个空格 :-) -
谢谢,彼得。我确实尝试了 {} 几次,但在第一段代码上仍然不是很好。
标签: hibernate