使用Spring JdbcTemplate进行多个数据库操作 [英] using Spring JdbcTemplate for multiple database operations

查看:730
本文介绍了使用Spring JdbcTemplate进行多个数据库操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢JdbcTemplate显而易见的简单性,但对它是如何工作有点困惑。似乎每个操作(query()或update())从数据源获取连接并关闭它。

I like the apparent simplicity of JdbcTemplate but am a little confused as to how it works. It appears that each operation (query() or update()) fetches a connection from a datasource and closes it.

很漂亮,但是如何在同一个连接中执行多个SQL查询?

Beautiful, but how do you perform multiple SQL queries within the same connection?

我可能想按顺序执行多个操作(例如SELECT后跟一个INSERT后跟一个提交)或者我可能想要执行嵌套查询(SELECT然后执行第二个SELECT基于每行的结果。)

I might want to perform multiple operations in sequence (for example SELECT followed by an INSERT followed by a commit) or I might want to perform nested queries (SELECT and then perform a second SELECT based on result of each row).

如何使用JdbcTemplate执行此操作。我使用的是正确的类吗?

How do I do that with JdbcTemplate. Am I using the right class?

推荐答案


如何执行多个SQL
查询在同一个连接中?

how do you perform multiple SQL queries within the same connection?

这里的正确答案是使用交易。如果您开始事务,然后使用 JdbcTemplate 执行多个操作,则每个操作都将在事务范围内,因此保证使用相同的连接。

The correct answer here is "use transactions". If you begin transaction and then perform multiple operations with JdbcTemplate, each of those operations will be within the scope of the transaction, and therefore are guaranteed to use the same connection.

如果您不想参与交易,那么另一种方法是在 JdbcTemplate上使用更原始的操作,如 execute(ConnectionCallback action),其中提供 ConnectionCallback 的实例,其中给出连接,然后您可以在其上执行您选择的任何操作。当然,但是这样做你不会在任何实际操作中获得 JdbcTemplate 的帮助。

If you don't want to get involved with transactions, then the alternative is to use the more primitive operations on JdbcTemplate, like execute(ConnectionCallback action), where you supply an instance of ConnectionCallback which is given a Connection, on which you can then perform any operations you choose. Of course, but doing this you don't get JdbcTemplate's help in any of the actual operations.

在Spring中交易非常简单,你应该考虑使用它们(参见上面的链接)。

Transactions are really quite easy in Spring, you should look into using them (see above link).

这篇关于使用Spring JdbcTemplate进行多个数据库操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆