hibernate - Why use @Transactional with @Service instead of with @Controller -


i have seen many comments in stack-overflow articles found things either @transactional use @service or @controller

"usually, 1 should put transaction @ service layer."

"the normal case annotate on service layer level"

"think transactions belong on service layer. it's 1 knows units of work , use cases. it's right answer if have several daos injected service need work in single transaction." [source]

drawback use @transactional @service layer

if had 2 methods example saveuser() , saveemail() (because store emails in database send them later - queue) create in service method saveuserandsendemail(user user) transactional. [source]

it means create many methods in service layer instead of 1 save generic method follow

public <t> long save(t entity) throws dataaccessexception {     session session = sessionfactory.getcurrentsession();     long getgenval=(long) session.save(entity);     return getgenval; } 

according above solution , means have many methods following lol..

public <t> long saveaccount(t entity)....

public <t> long savewithauditlog(t entity, k entity1)....

public <t> long savewithauditlogandentries(t entity, k entity, m entity)....

overcome situation

i use @transactional in @controller , make generic save method , save entities/ model using simple save method. , if method fail save transactions in controller rollback successfully.

other situation ensure @transactional should use @controller

in @controller:

pt.save(entity1); pt.save(entity2); int = 2/0; pt.save(entity3); 

in case , @transactional on service, first 2 entity saved third not not rollback transaction

in case , @transactional on @controller transaction rollback exception occur

why stack-overflow asked , "don't transactions in controller. put them in service layer classes."? [source]

you asking best practice, , best practice mark @transactional in service layer because @controller should not aware of data persistence in mvc logic.
@service constructed on use-case generated analysis , knows unit of works , realized thinking in terms of reuse: if switch web context desktop 1 (for example, or other visual frontend) @controller layer doesn't exist don't have problems because encapsulated in service layer.
@service contract , modification in presentation layer should not require rewrite of @service code.
spring don't care put your transaction boundaries, can put on @controller application may harder maintained.

i hope clear enough. sorry if not; english not native language.


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -