Your code is right as far as possible: you want to use the Spring @Transactional annotation for individual methods in your service class to get the necessary granularity, you are right that you want to SUPPORT for dontReadOrWrite (NOT_SUPPORTED suspends an existing transaction that will not buy you anything depending on what you have described, and will require your software to cycle, so there is no pain for profit), and you are correct that you want the default behavior (REQUIRED) for readSomething.
But it’s important to remember that Spring’s transactional behavior is that Spring implements transaction management by transferring your class to a proxy server that performs the appropriate transaction setup, calls your method, and then does the corresponding -down transaction when control returns. And (critically), this transaction control code is called only when the method is called on the proxy server, which does not happen if writeSomething () directly calls dontReadOrWrite (), as in your first brand.
If a method called by another method requires a different transactional behavior, you have two options that I know of if you want to use Spring @Transactional annotations to manage transactions:
- Move the method called by another to a different service class, which will be accessible from the original class of service through the Spring proxy.
- Leave the method it is in. Declare the member variable in your class of service the same type as your class of service interface and make it @Autowired, which will give you a reference to your proxy object of the Spring class. Then, when you want to call your method using different transactional behaviors, do it only for this member variable, not directly, and the Spring transaction code will fire as you want.
Approach # 1 is great if both methods are really unrelated to each other, because it solves your problem without confusing those who finish supporting your code, and there is no way to accidentally forget to call a method with transaction support.
Approach No. 2 is usually the best option, assuming that your methods are in the same service for some reason and that you do not want to separate them. But this is confused with an attendant who does not understand this Spring transaction wrinkle, and you must remember to refer to it this way in every place you call it, so there is a price for it. Usually I’m ready to pay this price so as not to tear my classes of service unnaturally, but, as always, it will depend on your situation.
source share