Skip to main content

Posts

Showing posts with the label JdbcTemplate

Spring JDBC RowMapper example

In this post, we will discuss what RowMapper is and how to use it when writing Jdbc code using Spring JDBC module. What is RowMapper? It is an interface of Spring JDBC module which is used by JdbcTemplate to map rows of java.sql.ResultSet . It is typically used when you query data. Example usage of RowMapper Let's first create a RowMapper which can map products. class ProductRowMapper implements RowMapper { @Override public Product mapRow(ResultSet rs, int rowNum) throws SQLException { Product product = new Product(); product.setId(rs.getInt("id")); product.setName(rs.getString("name")); product.setDescription(rs.getString("description")); product.setCategory(rs.getString("category")); return product; } } Now, we will use this ProductRowMapper in #queryForObject of JdbcTemplate . Product product = jdbcTemplate.queryForObject("select * from product where id=1", new Prod

Spring basic JdbcTemplate example

What is Spring JdbcTemplate? JdbcTemplate is the core class of Spring JDBC. It simplifies your interaction with low-level error prone details of JDBC access. You only pass the SQL statement to execute, parameters and processing logic for the returned data and rest is handled by it i.e. Opening Connection, transaction handling, error handling and closing Connection, Statement and Resultset. How to create object of JdbcTemplate? 1. Calling no args constructor. JdbcTemplate jdbcTemplate = new JdbcTemplate(); // You need to set datasource in later point in time and also have to call afterPropertiesSet. jdbcTemplate.setDataSource(DataSource ds); jdbcTemplate.afterPropertiesSet(); 2. By Calling constructor with datasource. JdbcTemplate jdbcTemplate = new JdbcTemplate(Datasource ds); 3. By Calling constructor with datasource and lazyInit parameter. JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSource dataSource, boolean lazyInit); Querying with JdbcTemplate There are ma