最近做了一个小东西,使用了Hibernate,想向大家请教一下关于对Hibernate事务处理,或者说小项目的事务处理方面的问题
最简单的方法是在每次Session打开后就开始事务,关闭前commit,可这样效率真的不敢恭维。
我的一个思路是,自己封装事务,意思是
public class UserTransaction{
private Transaction tran = null;
public UserTransaction(){
tran = getSession().beginTransaction();
}
protected Session getSession(){
return HibernateSessionFactory.getSession();
}
public void begin() throws TransactionException {
try {
tran.begin();
} catch (HibernateException e) {
TransactionException ex = new TransactionException(e.getMessage());
throw ex;
}
}
public void commit() throws TransactionException {
try {
tran.commit();
getSession().close();
} catch (HibernateException e) {
TransactionException ex = new TransactionException(e.getMessage());
throw ex;
}
}
public boolean isActive() throws TransactionException {
boolean token = false;
try {
token = tran.isActive();
} catch (HibernateException e) {
TransactionException ex = new TransactionException(e.getMessage());
throw ex;
}
return token;
}
public void registerSynchronization(Synchronization arg0) throws TransactionException {
// TODO Auto-generated method stub
}
public void rollback() throws TransactionException {
try {
tran.rollback();
getSession().close();
} catch (RuntimeException e) {
TransactionException ex = new TransactionException(e.getMessage());
throw ex;
}
}
public void setTimeout(int arg0) {
tran.setTimeout(arg0);
}
public boolean wasCommitted() throws TransactionException {
boolean token = false;
try {
token = tran.wasCommitted();
} catch (HibernateException e) {
TransactionException ex = new TransactionException(e.getMessage());
throw ex;
}
return token;
}
public boolean wasRolledBack() throws TransactionException {
boolean token = false;
try {
token = tran.wasCommitted();
} catch (HibernateException e) {
TransactionException ex = new TransactionException(e.getMessage());
throw ex;
}
return token;
}
}
这样一来就可以在业务层使用facade模式,开始时打开一个Session。放到ThreadLocal中,在最后commit后关掉
请高手指教,我对事务方面了解不多