簡體   English   中英

使用MyBatis和Spring與請求范圍進行交易

[英]Transaction with request scope with MyBatis and Spring

有沒有一種方法可以使用SpringMVC設置MyBatis以使整個HTTP請求具有一個事務? 通常在MyBatis中有類似Hibernate OpenSessionInViewFilter東西,還是應該編寫自己的過濾器來實現這種行為?

您對“會話”和“事務”概念感到困惑。 OSIV打開會話,在一個會話中可能會同時存在多個事務。 通常,應根據業務需求將@Transactional屬性放入控制器使用的服務。

而且,所有方面的一大交易就是反模式。 理想情況下,是對用戶的操作進行讀寫事務,然后另一個只讀事務是為用戶建立響應。 因為節省了用於插入/更新的數據庫鎖,所以它節省了資源。

您可以讓Spring處理您的交易。

看一下文檔。 我很容易 您只需要在需要它的方法中配置@Transactional注釋並將其添加。

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html

我的建議是閱讀以下幫助文檔: http : //static.springsource.org/spring/docs/3.0.5.RELEASE/reference/transaction.html

由於您無法完全控制spring-mvc框架的每個部分,因此建議您在spring-mvc的基類上使用aop切入點來啟動事務(在每個請求上執行的方法。) 10.5.2節中的方法。 只需確保切入點的類由spring otherwize初始化就不會起作用。

如果確實需要將單個事務綁定到特定請求,則可以考慮在Filter使用TransactionTemplate 我認為您不能在Filter上使用@Transactional ,除非它是由Spring管理的(例如:像Spring Security的Filters一樣的FilterChain一部分)。

這是您可以使用TransactionTemplate

public class TransactionalFilter implements Filter {
    private TransactionTemplate transactionTemplate;

    public void destroy() {
    }

    public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) throws ServletException, IOException {

        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                try {
                    chain.doFilter(req, resp);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ServletException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }

    public void init(FilterConfig config) throws ServletException {
        transactionTemplate = new TransactionTemplate(WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean(PlatformTransactionManager.class));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM