How to handle transactions using Spring JPA data?

I'm going to start creating a new application and would like some feedback on the approach I plan to use. We will use the spring and spring jpa data.

  • Can controllers call domain and repository services, or should the controller only make calls for applications and infrastructure services?

  • If it is β€œnormal” to call the domain services and repositories from the controller and the domain service operation, a transaction is required, can I / just put the @Transactional annotation in the domain service method? Or should I have an application service that ends the call (not sure if I like this approach because you will have a bunch of passes through methods)?

  • If it is not β€œnormal” to call domain services and repositories from the controller, do I need to create application services to wrap all possible calls to the domain service (as I said in 2, that there can be many ways to go through)?

The best solution I can come up with is something like the following:

  • Repositories will have an @Transactional annotation with the distribution REQUIRED when writing to the database and the distribution set for readOnly = true and the distribution set for SUPPORTS when reading from the database.

  • Domain applications and services will add @Transactional annotation as needed

If the dispatcher ever needs to make a direct call to the repository of a domain service or application service, he can. No passes.

enter image description here

+4
source share
2 answers

I do not understand your question. What do domain services do? I knew Application Services and Domain Repositories very well.

Spring has two levels of service and data access. The service level can be used by @Service (there will be Services applications in your design), but the @Transactional tag is not used.

The data access level uses the @Repository tag, as well as the @Transactional tag, because this level is directly connected to and works with the database. So, I like to know which domain service function. I dont understand what.

Thank you friend.

0
source

I personally would get access to your domain services and applications from your controllers. Thus, you should only put @Transactional annotations at the same level. You get the transaction out of the box at your repository level if you extend the regular Spring repository interfaces. I would leave this layer as simple as possible. Put your readOnly and other service level configuration.

Creating β€œpass” methods allows you more flexibility in the future if you ever decide to change your DAO implementation.

0
source

Source: https://habr.com/ru/post/1498641/


All Articles