spring - 无论如何都不是事务性的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(),该方法实际上会写入我的数据库。你能告诉我为什么吗?对不起我的英语不好。谢谢
解决方案
假设您的组件定义类似于以下内容:
@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 不是事务性的,更改仍会应用于数据库。
推荐阅读
- mysql - 返回 SQL 中特定行的计数
- python - 有没有办法阻止 QWindowsNativeFileDialog::OnSelectionChange(Qurl...) 退出命令行?
- sql - 如何在 WP_Query 中搜索标题、内容或元数据?
- r - 在带有 add_scatterplot 的点击事件期间,R 中的 Mapdeck 究竟返回了什么?
- html - 在调整窗口大小时调整元素大小
- python - 关于 range() 的 for 语句的问题
- javascript - nodejs https状态200但正文响应为空,ajax调用有效但返回错误状态0
- python - 为增强 Pascal Voc 数据集的原始图像添加类标签
- r - 如何根据函数参数重命名 R 中的对象?
- excel - Excel更改列格式和名称