Hibernate active transaction

孤街浪徒 提交于 2021-01-26 07:51:17

问题


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;
    }
  }
}

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?

Best regards


回答1:


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()

See the javadoc for Hibernate Transaction.




回答2:


Basically you can call session.beginTransaction(); in any case as it is specified by JavaDoc of Hibernate:

Begin a unit of work and return the associated Transaction object. If a new underlying transaction is required, begin the transaction. Otherwise continue the new work in the context of the existing underlying transaction.

But I would seriously consider the usage of a framework for transation management, like spring




回答3:


((SessionImpl)session).isTransactionInProgress()

This will return whether the transaction is active or not, without creating any new transaction.



来源:https://stackoverflow.com/questions/4854746/hibernate-active-transaction

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!