gpt4 book ai didi

java - Spring @Transactional 超时未按预期工作

转载 作者:搜寻专家 更新时间:2023-11-01 03:49:39 26 4
gpt4 key购买 nike

我有一个 JDBC 批量更新操作可能需要很长时间,因此我使用事务超时来处理这个问题。

@Override
@Transactional(propagation=Propagation.REQUIRES_NEW,timeout=10)
public void saveAllUsingBatch(List<KillPrintModel> list){
PreparedStatmentMapper ps= new HibernateDao.PreparedStatmentMapper<KillPrintModel>() {

@Override
public void prepareStatement(PreparedStatement ps, KillPrintModel t)
throws SQLException {
ps.setString(1, t.getOffice());
ps.setString(2, t.getAccount());
ps.setDate(3, new java.sql.Date(t.getUpdatedOn().getTime()));
}
};
String sql = String.format("INSERT INTO dbo.%s (%s,%s,%s) VALUES (?,?,?)",KillPrintModel.TABLE_NAME,KillPrintModel.FIELD_Office,KillPrintModel.FIELD_Account,KillPrintModel.FIELD_UpdatedOn);
this.jdbcBatchOperation(list, sql, ps);
}

即使我的交易时间超过 10 秒,此方法也会持续一分钟以上(并成功返回)。当超时为 0 时,它工作正常。


是不是因为我的线程一开始执行就一直处于运行状态?

最佳答案

如果在跟踪模式下调试没有帮助,只需在以下 hibernate 类中放置一个断点,它们最终会在 @Transactional Annotation 的 preparedstatement.setQueryTimeout(...) 中设置超时

org.hibernate.engine.jdbc.internal.StatementPreparerImpl
private void setStatementTimeout(PreparedStatement preparedStatement) throws SQLException {
final int remainingTransactionTimeOutPeriod = jdbcCoordinator.determineRemainingTransactionTimeOutPeriod();
if ( remainingTransactionTimeOutPeriod > 0 ) {
preparedStatement.setQueryTimeout( remainingTransactionTimeOutPeriod );
}
}

或者甚至更好,尽早进入事务管理器并单步执行,直到您命中 statement.setQueryTimout(..)。

org.springframework.orm.hibernate4.HibernateTransactionManager
int timeout = determineTimeout(definition);
if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
// Use Hibernate's own transaction timeout mechanism on Hibernate 3.1+
// Applies to all statements, also to inserts, updates and deletes!
hibTx = session.getTransaction();
hibTx.setTimeout(timeout);
hibTx.begin();
}
else {
// Open a plain Hibernate transaction without specified timeout.
hibTx = session.beginTransaction();
}

关于java - Spring @Transactional 超时未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31876975/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com