Spring JDBC

As mentioned earlier, Spring JDBC provides a layer of abstraction above the JDBC API. The JdbcTemplate class is the core of this layer. It helps you to manage connections and provides the workflow of interaction with the JDBC API. All you need to do is to prepare the statement and specify how you want to process the result set. The NamedParameterJdbcTemplate class wraps a JdbcTemplate object inside of it to provide the ability to use named parameters instead of a JDBC "?" placeholder.

Spring JDBC also provides SimpleJdbcInsert and SimpleJdbcCall to simplify JDBC operations by utilizing the metadata provided by the database. The metadata is retrieved by invoking the connection.getMetaData() method, which returns an instance of DatabaseMetaData. It includes information such as which tables are defined in the database and the columns that each table has. When using SimpleJdbcInsert and SimpleJdbcCall, you don't have to worry about the metadata. Spring takes care of that.

Spring JDBC also provides a way to model the JDBC operation as Java objects. You can create a MappingSqlQuery object to execute a database query, a SqlUpdate object to perform insert/update, and a StoredProcedure object to invoke a stored procedure on the database side. These objects are reusable and thread-safe.

We are going to use NamedParameterJdbcTemplate in MessageRepository. Here is what it looks like (the imports are omitted):

1.  public class MessageRepository { 
2. private static final Log logger =
LogFactory.getLog(MessageRepository.class);
3. private NamedParameterJdbcTemplate jdbcTemplate;
4. @Autowired
5. public void setDataSource(DataSource dataSource) {
6. this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
7. }

In line 3, we define the jdbcTemplate field of the NamedParameterJdbcTemplate type. And in lines 4 to 7, we use a setter method to ask Spring to inject DataSource so that we can instantiate the NamedParameterJdbcTemplate instance:

8.    public Message saveMessage(Message message) {
9. GeneratedKeyHolder holder = new GeneratedKeyHolder();
10. MapSqlParameterSource params = new MapSqlParameterSource();
11. params.addValue("text", message.getText());
12. params.addValue("createdDate",message.getCreatedDate());
13. String insertSQL = "INSERT INTO messages (`id`, `text`,
`created_date`) VALUE (null, :text, :createdDate)";
14. try {
15. this.jdbcTemplate.update(insertSQL, params, holder);
16. } catch (DataAccessException e) {
17. logger.error("Failed to save message", e);
18. return null;
19. }
20. return new Message(holder.getKey().intValue(),
message.getText(), message.getCreatedDate());
21. }
22. }

Inside the saveMessage() method, in line 9, we declare GeneratedKeyHolder, which will hold the generated id of the new message. And in lines 10 to 12, we prepare the parameters for the inserted SQL declared in line 13. As you can see, we use the named parameter text and createdDate as placeholders for parameters. Their names need to match the ones we used during parameter preparation in lines 11 and 12. And in lines 14 to 19, we ask jdbcTemplate to execute the SQL inside a try-catch block, because the update() method could throw DataAccessException whenever there is a JDBC operation error. And in line 20, we return the newly saved message.

As you can see, the implementation of the saveMessage() method using Spring JDBC is much simpler compared with interaction using the JDBC API directly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.97.216