我对 Spring Boot JDBC 模板的工作原理有疑问。我已阅读文档,但无法清楚地理解:(模板何时打开连接,何时关闭。事务如何处理。每次查询执行时它都会打开和关闭吗?
最佳答案
When does the template opens connection, when does it gets closed
为了构建 JdbcTemplate,您应该指定 JDBC 数据源来获取连接:
public JdbcTemplate(DataSource dataSource)
或者:
public JdbcTemplate()
JdbcAccessor.setDataSource(javax.sql.DataSource)
最终,JdbcTemplate
可与此 DataSource
配合使用。
DataSource
根据实现的不同,可能会返回未池化的新标准 Connection
对象或参与连接池的 Connection
对象。可以回收利用。
JdbcTemplate
已池化连接并将它们释放回数据源。
How does the transactions are handled
JdbcTemplate
依赖于数据库事务。
如果您想在服务层/业务逻辑上操作事务,则需要事务管理。
最简单的方法是使用 @Transactional
注释服务或使用 org.springframework.transaction.support.TransactionTemplate
。
关于java - Spring启动Jdbc模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44268244/