spring - Mixing JdbcTemplate and raw JDBC -
i experiencing strange behaviour can't explain. following code runs fine:
try (connection connection = datasource.getconnection(); statement statement = connection.createstatement()) { statement.executeupdate("delete product"); } catch (exception ex) { throw new runtimeexception(ex); } try (connection connection = datasource.getconnection(); statement statement = connection.createstatement()) { statement.executeupdate("insert product ..."); } catch (sqlexception ex) { throw new runtimeexception(ex); }
however code causes deadlock:
jdbctemplate.update("delete product"); try (connection connection = datasource.getconnection(); statement statement = connection.createstatement()) { statement.executeupdate("insert product ..."); } catch (sqlexception ex) { throw new runtimeexception(ex); }
the exception is
java.sql.sqlexception: lock wait timeout exceeded; try restarting transaction
both jdbctemplate , datasource created spring boot , autowired
@autowired private datasource datasource; @autowired private jdbctemplate jdbctemplate;
the statements form part of method in service (with @transactional annotation)
can explain why happens?
if want use own jdbc code plays nice connections managed spring's transaction management should use datasourceutils obtain connection -- see http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/datasource/datasourceutils.html#getconnection-javax.sql.datasource-
in example, depending on transaction configuration, first statement using jdbctemplate might not committed yet, block next jdbc statement different connection. using datasourceutils, both statements using same connection.
Comments
Post a Comment