Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

playframework - Where to place @Transactional annotation in Play

I am trying to connect my Play application with a database, I am following controller->service->DAO layer style.

Where should the @Transactional annotation be placed. In the controller action method or can I place it in a service layer class level/method level.

I tried keeping the @Transactional annotation in one of the Service layer class's method and it has thrown runtime error.

[RuntimeException: No EntityManager found in the context. Try to annotate your action method with @play.db.jpa.Transactional]

So, do we have to use @Transactional only on top of the controller actions? I am using play 2.4.2 version. If yes, why? As I am calling my DAO's in service layer the actual database operations will begin in service layer not in controller I guess. In controller, I am just calling the service layer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would recommend not to use @Transactional because it wraps entire action in an JPA transaction. It would be more efficient to start the transaction closer to db call.

I prefer starting the transaction at service level. Also it is important to note that db call is a blocking process so it must be executed outside of default action context.

Take a look at simple DAO+Service example https://gist.github.com/dzagorovsky/b8064c97ba647ed453ab

Also read about play thread pools here https://www.playframework.com/documentation/2.4.x/ThreadPools#Using-other-thread-pools

Blocking code (db calls) handling described here: https://www.playframework.com/documentation/2.3.x/JavaAsync


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...