Hibernate 多執行緒問題!

pliaozrlp發表於2009-06-10
程式如下:
//主呼叫程式
public void testGetPerson()throws Exception{

Thread A1 = new Thread(new A());
A1.start();
//A1.sleep(10000);
Thread A2 = new Thread(new A());
A2.start();
//A2.sleep(10000);
Thread A3 = new Thread(new A());
A3.start();
//A3.sleep(10000);
}
//執行緒定義
class A implements Runnable{

public void run() {
System.err.println(Thread.currentThread().getId()+"thread begin...");

Session se11 = HibernateSessionFactory.getSession();

System.err.println(Thread.currentThread().getId()+"opensession");

Transaction tx = se11.beginTransaction();

System.err.println(Thread.currentThread().getId()+"beginTran");

Person person = new Person();
person.setName(Thread.currentThread().getId()+"testName");
person.setSex("boy");
se11.save(person);

System.err.println(Thread.currentThread().getId()+"save");

tx.commit();
System.err.println(Thread.currentThread().getId()+"commit");
se11.close();
System.err.println(Thread.currentThread().getId()+"sessionclose");

}
}

這個程式中控制檯的輸出是:
9thread begin...
8thread begin...
10thread begin...
這樣就退出了。不知道是什麼問題,如果把執行緒sleep的方法去掉註釋就可以完成!大家幫忙看看,在此謝謝了!
HibernateSessionFactory是myeclipse自動生成的,它的主要方法是:
static{

try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}

/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();

if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}

return session;
}

[該貼被pliaozrlp於2009-06-10 11:36修改過]

相關文章