Hibernate活动事务

kun*_*gcc 7 hibernate

在我的服务类中,我希望有类似的东西:

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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

注意方法头后面的注释文本.我对Hibernate并不熟悉,但我认为如果服务方法检查事务是否存在,使用它,否则创建一个新的并关闭它会很好.

如果有可能,我是否应该考虑任何性能原因(或其他原因)?或者是否有其他方式来执行此类事情?

最好的祝福

jpk*_*ing 12

lweller的答案比我的答案更合适,但你可以通过调用来检查交易的状态 session.getTransaction().isActive()

查看用于Hibernate Transaction的javadoc .

  • 我认为, session.getTransaction() 肯定总是返回一个活动事务...所以不适合我(至少)...还有其他解决方案吗? (2认同)