Where to put the Transactional Spring annotation, in which layer?

I have doubts about placing Spring annotation in which layer? These are two cases:

  • case: placement @Transactional

    in a DAO layer

  • case: @Transactional

    service-level placement ?

I am only using Spring, not SpringMVC.

+3


source to share


3 answers


You want your services to be @Transactional

. If your DAOs are transactional and you are calling different DAOs on each service, then you will have multiple tansaction, which is not what you want. Make service calls @Transactional

and all DAO calls inside these methods will participate in the transaction for that method.



See this link for details

+4


source


Put it in the service tier as the service might want to access multiple DAO methods, but they will still be considered part of the same business transaction .



+3


source


transaction usually means that you want to group multiple transactions together for example:

void bankTransfer(String fromAccount, String toAccount, BigDecimal amount)
{
if (amount.compareTo(BigDecimal.ZERO) < 0) throw new RuntimeException("hack attempt");
accountDao.deduct(fromAccount, amount);
accountDao.add(toAccount, amount);
}

      

here bank transfer has logic. The dao account has no logic, they just subtract and add.

+2


source







All Articles