[JdbcTemplate] How to write a query (SELECT statement)


How to write Query with JdbcTemplate!
(Cases of retrieving one or multiple records with a SELECT statement)



We will explain assuming that the User class has the following table (users) and stores it.

users table

User class


Get Data

I will explain the case where only one record and multiple records are acquired.

How to get with Map

Get only 1

Create SQL statementCreate SQL statementGet the query result in the form of Map<String, Object>


Get multiple

Get the query result with List<Map<String, Object>>.


How to get with RowMapper (requires preparation)

You need to prepare your own mapper that implements the RowMapper interface.


Create a class that implements RowMapper interface.
(Only 1 case, common to multiple cases)


Get only 1

Receive mapping result that implements RowMapper interface.


Get multiple

Receive the result of implementing RowMapper interface in List.


How to get with BeanPropertyRowMapper (no preparation required!)

No need to create a class that implements the RowMapper interface!

If the column name of the table and the field name of the mapping class are the same,
It will set the value automatically.

Applicable example

  • snake case
    Table column name: user_id
    Class field name: userId
  • Same case
    Table column name: id
    Class field name: id

* In the class to store (in this case, User class),
 It is assumed that there is a Default Constructor and a setter.
If you’re using Lombok, either the @Setter annotation or
It would be nice to have the @Data annotation.

Get only 1


Get multiple

Which one is better?

First : BeanPropertyRowMapper

Easiest way to map.
If setters are allowed, use them.

If you can’t use the setter (need to convert to ValueObject),
It can be implemented with RowMapper.

Second : RowMapper

Creating a class to map is a little troublesome.

However, if you create it, you can get one and multiple things like Map in two places
There is no need to write the setter process to the User class each time.

You can use it when you want to define your own mapping class.

Third : Map

Because it is necessary to write to store the query acquisition result in the User class,
Not recommended in terms of time and maintenance.


Let's share this post !

Author of this article


To comment