Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to add transaction Management to Controller by SSM

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "how to add transaction management in Controller by SSM". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to add transaction management in SSM in Controller" can help you solve the problem.

SSM adds transaction management to Controller

I use:

Integrated development environment: idea

Project management tool: maven

Database: oracle

Frame: Spring+SpringMVC+myBatis

In general, transactions are added to the Service layer, but they can also be added to the Controller layer.

After reading many people's blogs, I summed up two methods:

Write programmatic transactions at the controller layer

Define the transaction configuration in the application context (spring-mvc.xml) of Spring MVC

Now let's talk about how to achieve it:

1. Writing programmatic transactions at the controller layer [tedious, not recommended]

The configuration of the transaction manager in spring-mybatis.xml remains the same.

Write a transaction in a method in controller

/ / inject transactionManager@Resourceprivate PlatformTransactionManager transactionManager; @ PostMapping (value = "setCode") @ ResponseBodypublic void setCode (Invoice invoice, InvoiceAddress invoiceAddress,String token,String orderIDs, Integer pid,HttpServletResponse response) {DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition (); defaultTransactionDefinition.setPropagationBehavior (TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = transactionManager.getTransaction (defaultTransactionDefinition) in each controller; try {invoiceService.insert (token,pid,invoice); int iID= invoice.getId () String substring = orderIDs.substring (0, orderIDs.length ()-1); String [] split = substring.split (","); for (String string2: split) {bOrderService.updateIStatus ("1", string2);} invoiceOrderService.insert (iID,substring); if (Integer.parseInt (invoice.getiType ()) = = 1) {invoiceAddressService.insert (iID,invoiceAddress) } System.out.println ("= make a run-time exception aa="); System.out.println ("run-time exception:" + 100apper0); / / manually commit the transaction transactionManager.commit (status) without exception; printJson (response,result (200, "ok")) } catch (Exception e) {/ / rollback transaction transactionManager.rollback (status) if there is an exception; e.printStackTrace (); printJson (response,result (500, "false"));}} 2. Define transaction configuration in the application context (spring-mvc.xml) of Spring MVC [straightforward, once and for all]

The configuration of the transaction manager in spring-mybatis.xml remains unchanged.

The transaction configuration is also defined in spring-mvc.xml:

Type the @ Transactional (rollbackFor = {Exception.class}) comment on Controller

@ Controller@RequestMapping (value = "/ invoiceC") @ Transactional (rollbackFor = {Exception.class}) public class InvoiceController extends BaseController {@ Autowired private InvoiceService invoiceService; @ Autowired private InvoiceOrderService invoiceOrderService; @ Autowired private InvoiceAddressService invoiceAddressService; @ Autowired private BalanceRechangeOrderService bOrderService PostMapping (value = "setCode") @ ResponseBody public void setCode (Invoice invoice, InvoiceAddress invoiceAddress,String token,String orderIDs, Integer pid,HttpServletResponse response) {invoiceService.insert (token,pid,invoice); int iID= invoice.getId (); String substring = orderIDs.substring (0, orderIDs.length ()-1) / / intercept the last String [] split = substring.split (","); / / split for (String string2: split) {bOrderService.updateIStatus ("1", string2) {bOrderService.updateIStatus ("1", string2);} invoiceOrderService.insert (iID,substring); if (Integer.parseInt (invoice.getiType ()) = = 1) {/ / Paper invoice, receiving address invoiceAddressService.insert (iID,invoiceAddress) } System.out.println ("= make a run-time exception aa="); System.out.println ("run-time exception:" + 100apper0); printJson (response,result (200,200, "ok");}}

Now, let's talk about why before? = "

Add declarative transaction interception to Controller in spring-mybatis.xml

Add @ Transactional to Controller's class

Neither of them has taken effect.

Principle: because spring containers and spring-mvc are parent-child containers. When the server starts, the web.xml configuration file will be loaded first = > then the spring configuration file will be loaded = > and then back to web.xml [load listeners; load filters; load front-end controllers] = > and then load the springMVC configuration file

In the Spring configuration file, we scan and register the service implementation class, and even if the scan registers the controller, it will load the SpringMVC configuration file [scan Registration controller] to overwrite it, so if you want to achieve transaction management in controller, only in the spring configuration file configuration or no effect, you must define the transaction configuration in the SpringMVC application context (spring-mvc.xml).

Because it is stated in the spring-framework-reference.pdf document:

Only the @ Transactional annotation above the bean defined in the same application context file will be found

Transaction configuration of Controller layer under SSM

In the process of writing the project encountered multi-table joint modification of data transaction problems, according to the previous study, transactions are configured in the service layer, but in my project module, a service corresponds to a data table, so I want to add a data modification and added transaction configuration for multiple tables in the controller layer. Tragically, an error in configuring a transaction in the controller layer is not rolled back!

According to the logic I have come into contact with, it is not recommended to write business logic in the control layer, so what is called is the interface of multiple service layers (using Autowired) to invoke business operations of multiple tables. But multiple tables form a single transaction, so I didn't find an appropriate way to add transactions separately in the service layer. If any seniors come up with a suitable method, please give me some advice! Thank you!

Solve

Original configuration

The first step is to add the transaction configuration on the service layer. My transaction processing here is annotated, so the configuration file is much simpler than configuring the transaction.

First, add the following to the namespace

Xmlns:tx= "http://www.springframework.org/schema/tx"http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd

Then there is the configuration of the xml file:

Among them, the data source I configured in the dao layer configuration file, because they are all under the management of spring, so the direct use of service can be found.

Here is the version of the jar package on which my maven depends:

Org.springframework spring-tx 5.1.5.RELEASE org.springframework spring-jdbc 5.1.5.RELEASE

The above is my initial configuration. But this alone cannot add transactions to the controller layer.

Revised configuration

If we want to add a transaction to the service layer when the configuration file of the controller layer remains unchanged, we only need to introduce an annotation-driven tag for the transaction in the spring-mvc.xml.

Why is this?

First, let's look at the loading of the configuration file:

DispatcherServlet org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:spring-mvc.xml DispatcherServlet * .action org.springframework.web.context.ContextLoaderListener contextConfigLocation classpath:spring-*.xml

The above is part of my web.xml configuration. During the project startup process, the spring-mvc.xml is loaded using DispatcherServlet, while the spring-service.xml and spring-dao.xml are loaded using ContextLoaderListener.

Then we need to know that ContextLoaderListener is started before DispatcherServlet, and controller is not loaded into the container when ContextLoaderListener loads the service layer configuration, but at this point the dynamic proxy for the transaction has been cut into the service layer, so the subsequent controller layer has not been enhanced.

Therefore, we need to join again in the controller layer.

This is the end of the introduction to "how SSM can add transaction management to Controller". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report