我已经创建了一个用于处理 hibernate 的 dbadapter。实际上我的类看起来像这样..
public class DBAdapter {
private static SessionFactory factory;
private static final ThreadLocal<Session> threadSession = new ThreadLocal();
public static Session OpenConnection() {
if (factory == null) {
factory = new Configuration().configure(
"com/et/hibernatexml/hibernate.cfg.xml")
.buildSessionFactory();
}
Session s = (Session) threadSession.get();
if (s == null)
{
s =factory.openSession();
threadSession.set(s);
}
return s;
}
public List selectQuery(String QueryString)
{ try
{
Session session=OpenConnection();
resultlist = query.list();
}
finally()
{
closeSession();
}
}
public static void closeSession()
{
Session session = (Session) threadSession.get();
threadSession.set(null);
if (session != null && session.isOpen()) {
session.flush();
session.close();
}
}
为了从服务器获取数据,我会这样做..
DBAdapter ob=new DBAdapter();
ob.setParameter("orgId", orgId);
List list=ob.selectQuery(queryvalue);
我怀疑这样处理是否会出现问题。特别是因为 SessionFactory 是静态变量??
最佳答案
您不希望多个线程创建 session 工厂。它应该是单例,并且设计上是线程安全的。使用您提供的代码执行此操作的最简单方法是在 openConnection() 方法上使用同步关键字。但是,没有理由同步创建 session 并将其也放在 ThreadLocal 实例上的代码部分。粗略的解决方案如下所示
public class DBAdapter {
private static SessionFactory factory;
private static final ThreadLocal<Session> threadSession = new ThreadLocal<Session>();
private static synchronized SessionFactory getSessionFactory() {
if(factory == null) {
factory = new Configuration().configure("com/et/hibernatexml/hibernate.cfg.xml").buildSessionFactory();
}
return factory;
}
public static Session getSession() {
Session s = (Session) threadSession.get();
if (s == null) {
s = getSessionFactory().openSession();
threadSession.set(s);
}
return s;
}
}
关于java - 在Hql-Initialization中创建sessionFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14579380/