2

I have my services like this annotated with @Transactional

@Transactional
@Service
public class Contact_Service {
   ....

In my Controller i don't have @Transactional and sometimes i use some persistence layer methods directely to search and persist my object and everything is okey :

@Controller
public class GestionAO {

    ....

    @RequestMapping(...) 
    public String alerte() {

                contact_respository.findOne(...) ;
                ...
                contact_respository.save(...) ;

My question since my controller is not in a transaction will i got some problems ?
Can my object don't get saved in some cases ?
Will i got concurrence problem ?

Hayi
  • 6,972
  • 26
  • 80
  • 139
  • Although it looks fine it also looks like you are having business logic in your web layer. The web layer should be a thin layer exposing service logic. What now is in your `alerte` method should be a service method annotated with `@Transactional` and your `alerte` method should call that service method. That way you can also easily test your business logic. – M. Deinum Dec 22 '14 at 08:34

3 Answers3

4

Looks fine now when you have only one save call. If there are multiple DML or DDL operations executed from the Controller you will lose on not having transaction management. You will lose on the ACID behavior that transactions offer.

Community
  • 1
  • 1
Andy Dufresne
  • 6,022
  • 7
  • 63
  • 113
4

The purpose of having @Transactional annotation is to perform multiple database operations in a single transaction. If one operation fails, entire transaction should be roll-backed. Otherwise this can cause data integrity issues.

And the most important thing is to have @Transactional on service layer methods. Because that's one layer who knows unit of work and use cases. In some cases you will have to call multiple DAO layer methods, those all operations are called from service layer and mostly from single method. So it is always better to annotate your service layer methods as @Transactional.

To sum it up, You must have @Transactional annotations on service layer methods.

Jeevan Patil
  • 6,029
  • 3
  • 33
  • 50
2

you should only annotate service with @Transactional. to make sure all of db operations under single transaction, it is recommended to add a new method in service which contains all you db operations, and just call this new method in controller.

Septem
  • 3,614
  • 1
  • 20
  • 20