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

Pay attention to the comment after the chapter of the method. I am not very familiar with Hibernate, but I think it would be great if the service methods checked if a transaction exists, use it, otherwise create a new one and close it.

If possible, are there any performance considerations (or others) that I should keep in mind? Or is it some other way to accomplish such things?

Best wishes

+7
source share
3 answers

Lweller's answer is a more suitable approach than my answer, but you can check the status of a transaction by calling session.getTransaction().isActive()

See javadoc for Hibernate Transaction .

+12
source

Basically, you can call session.beginTransaction(); In any case, since it is specified by JavaDoc from Hibernate:

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

But I would seriously consider using a framework for managing translations like spring

+3
source
 ((SessionImpl)session).isTransactionInProgress() 

Returns information about whether a transaction is active or not, without creating a new transaction.

0
source

All Articles