首页 > 解决方案 > 无论如何都不是事务性的spring方法

问题描述

我在一个项目中有一个主实例,它实例化了一个名为 AnagrafePfDaoImpl(意大利语/英语名称)的 DAO。这个 DAO 有这些声明:

<bean id="AnagrafePfDaoImpl"
    class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="transactionManager">
        <ref bean="transactionManager" />
    </property>
    <property name="target">
        <ref bean="anagraficaDAOTarget" />
    </property>
    <property name="proxyTargetClass" value="true" />
    <property name="transactionAttributes">
        <props>
            <prop key="insert*">PROPAGATION_REQUIRED, ISOLATION_READ_COMMITTED</prop>
            <prop key="update*">PROPAGATION_REQUIRED, ISOLATION_READ_COMMITTED</prop>
            <prop key="merge*">PROPAGATION_REQUIRED, ISOLATION_READ_COMMITTED</prop>
            <prop key="salva*">PROPAGATION_REQUIRED, ISOLATION_READ_COMMITTED</prop>
            <prop key="delete*">PROPAGATION_REQUIRED, ISOLATION_READ_COMMITTED</prop>
            <prop key="search*">PROPAGATION_REQUIRED, ISOLATION_READ_COMMITTED</prop>
            <prop key="find*">PROPAGATION_REQUIRED, ISOLATION_READ_COMMITTED,readOnly</prop>
            <prop key="get*">PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED,readOnly</prop>
        </props>
    </property>
</bean>

我假设如果我在 AnagrafePfDaoImpl 中调用一个名为 doStuff() 的方法,例如在其中执行更新,则除非从具有自己事务的方法调用,否则这不会产生任何影响。但我错了,因为如果我从我的主类(没有声明)调用 doStuff(),该方法实际上会写入我的数据库。你能告诉我为什么吗?对不起我的英语不好。谢谢

标签: springtransactions

解决方案


假设您的组件定义类似于以下内容:

@Component
public class AnagraficaDAOTarget {

  @Autowired
  DataSource dataSource;

  public long doStuff(String message) throws Exception {
    long id;
    try(Connection connection = dataSource.getConnection()) {
      id = getId(connection);
      try (PreparedStatement statement = connection.prepareStatement("insert into comment (id, message) values (?, ?)")) {
        statement.setLong(1, id);
        statement.setString(2, message);
        int count = statement.executeUpdate();
        if (count != 1) {
          throw new Exception("expected one row insert, actual: " + count);
        }
      }
    }
    return id;
  }
} 

然后 Connection 处于自动提交模式,因此即使 doStuff 不是事务性的,更改仍会应用于数据库。


推荐阅读