Reputation: 159
I'm using Spring jdbcTemplate for my DAO layer. And i have at least two sql statements that i want to execute in a single query to hit the database once:
String INSERT_SQL = "INSERT INTO \"ADDRESS\" (id_registred_user, "
+ "address, "
+ "city, "
+ "region, "
+ "country) "
+ "VALUES (?, ?, ?, ?, ?)";
String UPDATE_SQL = "UPDATE \"REGISTRED_USER\" SET id_address = ? "
+ "WHERE id_registred_user = ?";
For now i'm doing this inside @Transactional:
jdbcTemplate.update(INSERT_SQL, args...);
jdbcTemplate.update(UPDATE_SQL, args...);
I know that in simple jdbc there is an addBatch() method, but how can i execute these two sql statements in a single batch using jdbcTemplate? Is there an addBatch() equivalent in jdbcTemplate?
Thanks in advance.
Upvotes: 4
Views: 20821
Reputation: 32507
You could concatenate both queries and add ;
as separator, but this will not make those queries "atomic". In other words, they will not be executed at once as you think, but one after another, just like you would execute 2 templates one by one - no difference here.
To guarantee operation atomicity, you have to use transactions. Transactions can make all changes made by the queries apply at once on transaction commit.
Upvotes: 5