Search code examples
springtimeoutspring-transactions

Is there a way of setting a real-time timer for for the transaction timeout of DataSourceTransactionManager in Spring?


As I know, the default behavior of the transaction timeout in Spring DataSourceTransactionManager is that it checks the start time of a transaction and sets the limit time of the transaction, based on the transaction AOP settings. After these, it checks if the current time exceeded the limit time every time the transaction executes a query with the DataSource, and if so, the TransactionManager throws TransactionTimedOutException.

Because of the above, I can't depend on the transaction limit time when a transaction service has only one query execution.

Is there a way of setting a real-time transaction timer for the DataSourceTransactionManager, which is based on timer threads?


Solution

  • Statement / Query-level timeouts (vs. a transaction-level timeouts) might work for you. There are many ways to set them, depending on your setup:

    • The javax.persistence.query.timeout query hint
    • Hibernate's Query.setTimeout()
    • JDBCTemplate.setQueryTimeout() (this can also be set globally)
    • With plain JDBC we can set query timeout on Statement and PreparedStatement

    Statement-level timeouts require driver support so the behavior can vary by implementation. Also, they're not guaranteed to work if there are unusual situations like a network issue (but you can usually set network-level timeouts as well.)