Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

java - using Spring JdbcTemplate for multiple database operations

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.

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

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).

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...