1

If I have a basic Dao class that is marked as @Transactional on class level, this will cause every call of the Dao to run in it's own transaction.

What if I create a method somewhere which uses multiple calls to different dao methods? Will each of these calls run in its own transaction, or will the transaction be wrapped around?

@Service
@Transactional
class BaseDao<T> {
    //each of these methods will run in a transaction
    public void save(T entity) { }
    public void update(T entity) { }
}

@Service
class PersonFacade() {
    //will this "wrapp" the transaction?
    @Transactional
    void update() {
        dao.find();
        dao.update();
    }
}

If it is wrapped, would you consider it then a good practice having the @Transactional annotation on a generic Dao class, so that the dao might be used directly as @Autowired BaseDao<Person> to manage CRUD operations? And only if needed, create facades that wrap up multiple crud calls that need to run within a single transaction?

Or should I remove that transactional from the base dao better?

membersound
  • 81,582
  • 193
  • 585
  • 1,120

1 Answers1

1

If you wrap both calls into a method that is also marked @Transactional, then there will be just one transaction to span everything.

I think DAO classes should not have @Transactional annotations. Put those into a Service class that provides "business methods". Only those will know which DAO method calls (from possibly multiple entities) to compose into meaningful transactions.

See also Where does the @Transactional annotation belong?

Community
  • 1
  • 1
Thilo
  • 257,207
  • 101
  • 511
  • 656