Spring JdbcTemplate¶
Introduction ¶
Spring JdbcTemplate is a powerful mechanism to connect to the database and execute SQL queries. It internally uses JDBC api, but eliminates a lot of problems of JDBC API.
Advantage of Spring JdbcTemplate ¶
Spring JdbcTemplate eliminates all the problems of JDBC API. It provides you methods to write the queries directly, so it saves a lot of work and time.
1. Opens connection.
2. Prepares and executes statements.
3. Set up the loop to iterate through the results.
4. Process any exception.
4. Handle transactions.
5. Close the connection, statement, and resultset.
Spring Jdbc Approaches ¶
Spring framework provides following approaches for JDBC database access:
JdbcTemplate NamedParameterJdbcTemplate SimpleJdbcTemplate SimpleJdbcInsert and SimpleJdbcCall
JdbcTemplate class ¶
For Insertion/deletion/updation we can use the method like update/update args
i.e
1 2 | |
Ex : For Insert/delete/Update ¶
1 2 | |
Ex : For Batch Insertion ¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
Ex : For Retrieving the data ¶
If we want to Retrieve the data from select query which is only one distinct element like we are using queryForObject i.e
1 2 | |
here we can retrieve the objects like i.e String,Integer,Boolean etc...
Ex : For Retrieving the Result set data ¶
To Fetch the records from the database we are using two techniques i.e ResultSetExtractor RowMapper interfaces
But if we facilitate mapping between columns and fields of pojo class we are using advanced technique using
BeanPropertyRowMapper
There are several built-in classes that directly map the result set to a list of objects,
for example, BeanPropertyRowMapper.
i.e
1 2 3 4 5 6 7 8 9 | |
Ex : For Executing normal StoredProcedure ¶
For executing normal stored Procedure we are following technique.
1 2 | |
Ex : For Executing StoredProcedure with OUT Parameter¶
If we are executing the simple StoredProcedure with OUT Parameter. We are using SimpleJdbcCall
Ex:
1 2 3 4 5 6 7 8 | |