休眠活跃交易 [英] Hibernate active transaction
问题描述
在我的服务班上,我想做些类似的事情:
In my service class I would like to have something like:
class ClientService {
// Authorize
// Returns true: Authorization successful
// Returns false: Authorization failed
public boolean authorize(String id, String password) {
//Here I would like to check if an active transaction exists.
//If it exists, use that one, else create a new session and start
//a new transaction.
//For example:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
if(!session.SOMEMETHOD_CHECK_IF_TRANSACTION_IS_ACTIVE) {
session.beginTransaction();
}
Client client = clientDAO.get(id);
if (client != null) {
if (client.getPassword().equals(password)) {
logger.debug("Authorization successful. ID: " + client.getId() + ", password: " + client.getPassword());
return true;
} else {
logger.error("Authorization unsuccessful");
return false;
} else {
logger.debug("Authorization unsuccessful. No client exists with ID: " + id);
return false;
}
}
}
在方法标题之后注意注释的文本.我对Hibernate不太熟悉,但是如果服务方法检查事务是否存在,使用它,否则创建一个新事务并关闭它,那会很好.
Notice the commented text after the method head. I'm not so familiar with Hibernate, but I think it would be great if the service methods check if transaction exists, use it, otherwise create a new one and close it.
如果有可能,我是否应该考虑任何性能原因(或其他原因)?还是执行这种事情的其他方法?
If it is possible, is there any performance reasons (or others) that I should have in mind? Or is it any other way to perform this kind of thing?
最诚挚的问候
推荐答案
lweller的答案比我的答案更合适,但是您可以通过调用 session.getTransaction().isActive()
lweller's answer is a more appropriate approach than my answer, but you can check the state of a transaction by calling session.getTransaction().isActive()
有关休眠事务,请参见Javadoc.
See the javadoc for Hibernate Transaction.
这篇关于休眠活跃交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!