简体   繁体   English

如何在Spring JDBC中使用Guice进行事务处理

[英]How to use transaction in Spring JDBC with Guice

I am new to Spring JDBC. 我是Spring JDBC的新手。 I have created a DAO which has interface like: 我创建了一个DAO,其界面如下:

@ImplementedBy(StuffDAOImpl.class)
public interface StuffDAO {
    void createStuff(StuffDTO stuffDTO);
    @Transactional
    void updateStuff(StuffDTO stuffDTO);
}

How can I config updateStuff to be transactional, for example, if there are two updates in the method: 如何将updateStuff配置为事务性,例如,如果方法中有两个更新:

@Override
@Transactional
public void updateStuff(StuffDTO stuffDTO) {
    String query = "UPDATE stuff SET (name, username, password) = (?, ?, ?) WHERE rowid = 10";
    getJdbcTemplate().update(query, new Object[]{"John", "john", "12345"});

    // This will fail
    try {
        String wrongquery = "UPDATE tablenotexist SET (name, username, password) = (?, ?, ?) WHERE rowid = 10";
        getJdbcTemplate().update(wrongquery, new Object[]{"John", "john", "12345"});
    }catch (BadSqlGrammarException e) {
        // IGNORE
    }
}

In the above example, the second query will fail because it trying to update a table that does not exist. 在上面的示例中,第二个查询将失败,因为它尝试更新不存在的表。 I think by declaring this method works as one transaction, it should serve the purpose. 我认为通过声明此方法作为一个事务,它应该服务于目的。 However it does not seem to work. 但它似乎不起作用。

How can I make the query one also rollback if this method runs? 如果此方法运行,如何使查询也回滚?

By the way, I use Guice instead of Spring to do DI. 顺便说一句,我使用Guice而不是Spring来做DI。

Many thanks 非常感谢

You're using Spring JDBC, Spring transactions, but Guice for DI? 您正在使用Spring JDBC,Spring事务,但是Guice for DI? Why? 为什么? You're making things much more complex than needed. 你制造的东西比需要的要复杂得多。

Your objects are probably not Spring beans, since Spring doesn't create and inject them, so @Transactional has no effect: Spring doesn't create and inject the objects, so it doesn't create and inject transactional proxies, so the annotation is never used by anything. 你的对象可能不是Spring bean,因为Spring不会创建和注入它们,所以@Transactional没有效果:Spring不会创建和注入对象,所以它不会创建和注入事务代理,所以注释是从未使用过任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM