Spring
JdbcTemplate
batch insert, batch update and also @Transactional
examples.Apr 4, 2011 - Here's an example to show you how to update a record in a table via JDBC statement. To issue a update statement, calls the Statement. JDBC - Update Records Example. Previous Page. Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to update records in a table. This Query makes use of IN and WHERE clause to update conditional records.
Technologies used :
- Spring Boot 2.1.2.RELEASE
- Spring JDBC 5.1.4.RELEASE
- Maven 3
- Java 8
1. Batch Insert
1.1 Insert a batch of SQL Inserts together.
1.2 If the batch is too big, we can split it by a smaller batch size.
BookRepository.java
2. Batch Update
2.1 Same to SQL update statement.
2.2 Update by batchSize.
BookRepository.java
3. Run
3.1 Create a table to test the batch insert and update.
Output
4. @Transactional
4.1 With
@Transactional
, any failure causes the entire operation to roll back, none of the books will be added.BookRepository.java
4.2 Try batch insert a 1000 books, the #500 contains an error, and the entire batch will be rolled back, no book will be inserted.
Output
Download Source Code
$ git clone https://github.com/mkyong/spring-boot.git
$ cd spring-jdbc
$ cd spring-jdbc
References
- Spring Boot JDBC Examples_
About the Author
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.![Dynamic Update Query In Jdbctemplate Javatpoint Dynamic Update Query In Jdbctemplate Javatpoint](https://dz2cdn2.dzone.com/storage/article-thumb/1500561-thumb.jpg)
Comments
![Jdbctemplate query method Jdbctemplate query method](/uploads/1/2/6/2/126295336/530853741.png)
- JDBC Tutorial
- JDBC Examples
- JDBC Useful Resources
- Selected Reading
Following is the example, which makes use of the following three queries along with the opening and closing statement −
- boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use the truly dynamic SQL.
- int executeUpdate(String SQL): Returns the number of rows affected by the execution of the SQL statement. Use this method to execute SQL statements, for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement.
- ResultSet executeQuery(String SQL): Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement.
This sample code has been written based on the environment and database setup done in the previous chapters.
Copy and past the following example in JDBCExample.java, compile and run as follows −
Now let us compile the above example as follows −
When you run JDBCExample, it produces the following result −
jdbc-statements.htm