JdbcTemplate in Spring Framework: Best Practices for Java Querying

A bunch of examples of using jdbcTemplate in Spring framework (Java)1 min


-1
-1 points
Spring-jdbcTemplate-Examples-—-Java

Learn how to use JdbcTemplate for efficient database querying in Spring Java. Master Spring’s JdbcTemplate for seamless queries.

Let me give you most of the useful examples about “How to use jdbcTemplate in java!”, To query or extract data from the database.

Technology:
  • Spring Boot
  • Spring JDBC
  • Maven 3
  • Java 8
TL;DR

Use jdbcTemplate.query for multiple rows or list

Use jdbcTemplate.queryForObject for single row or value


Cover Image Credits: Image by Author | Spring jdbcTemplate Examples — Java

Learn how you can query and extract data.

1. Query for Multiple Row

For multiple rows, we use jdbcTemplate.query()

 public List findAll() {
    
        String sql = "SELECT * FROM CUSTOMER";

        List customers = jdbcTemplate.query(
                sql,
                new CustomerRowMapper());

        return customers;
        
    }

Use BeanPropertyRowMapper — It will reduce your manual row mapping efforts [Recommended]

public List findAll() {

        String sql = "SELECT * FROM CUSTOMER";

        List customers = jdbcTemplate.query(
                sql,
                new BeanPropertyRowMapper(Customer.class));

        return customers;
    }

Take benefits of java 8 for row mapping with resultset data.

public List findAll() {

        String sql = "SELECT * FROM CUSTOMER";

        return jdbcTemplate.query(
                sql,
                (rs, rowNum) ->
                        new Customer(
                                rs.getLong("id"),
                                rs.getString("name"),
                                rs.getInt("age"),
                                rs.getTimestamp("created_date").toLocalDateTime()
                        )
        );
    }

jdbcTemplate.queryForList, it works, but not recommend, the mapping in Map may not same as the object, need casting.

public List findAll() {

        String sql = "SELECT * FROM CUSTOMER";

        List customers = new ArrayList<>();

        List> rows = jdbcTemplate.queryForList(sql);

        for (Map row : rows) {
            Customer obj = new Customer();

            obj.setID(((Integer) row.get("ID")).longValue());
            obj.setName((String) row.get("NAME"));
            // Spring returns BigDecimal, need convert
            obj.setAge(((BigDecimal) row.get("AGE")).intValue()); 
            obj.setCreatedDate(((Timestamp) row.get("CREATED_DATE")).toLocalDateTime());
            customers.add(obj);
        }

        return customers;
    }

2. Query for Single Row

In Spring, we can use jdbcTemplate.queryForObject() to query a single row record from the database, and convert the row into an object via row mapper.

import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;

public class CustomerRowMapper implements RowMapper {

    @Override
    public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {

        Customer customer = new Customer();
        customer.setID(rs.getLong("ID"));
        customer.setName(rs.getString("NAME"));
        customer.setAge(rs.getInt("AGE"));
        customer.setCreatedDate(rs.getTimestamp("created_date").toLocalDateTime());

        return customer;

    }
}

Now, Bind resultset value with Custom Row Mapper (*DaoImpl.java)

import org.springframework.jdbc.core.JdbcTemplate;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    public Customer findByCustomerId(Long id) {

        String sql = "SELECT * FROM CUSTOMER WHERE ID = ?";

        return jdbcTemplate.queryForObject(sql, new Object[]{id}, new CustomerRowMapper());

    }

Spring BeanPropertyRowMapper, this class saves you a lot of time for the mapping. [Recommended]

This class saves you a lot of time for mapping.

import org.springframework.jdbc.core.BeanPropertyRowMapper;
    
    public Customer findByCustomerId2(Long id) {

        String sql = "SELECT * FROM CUSTOMER WHERE ID = ?";

        return (Customer) jdbcTemplate.queryForObject(
            sql, 
            new Object[]{id}, 
            new BeanPropertyRowMapper(Customer.class));

    }

In Java 8, We can map directly;

public Customer findByCustomerId3(Long id) {

        String sql = "SELECT * FROM CUSTOMER WHERE ID = ?";

        return jdbcTemplate.queryForObject(sql, new Object[]{id}, (rs, rowNum) ->
                new Customer(
                        rs.getLong("id"),
                        rs.getString("name"),
                        rs.getInt("age"),
                        rs.getTimestamp("created_date").toLocalDateTime()
                ));

    }

3. Query for Single Value

It’s the same like query a single row from the database, uses jdbcTemplate.queryForObject()

Count Query

public int count() {
 String sql = "SELECT COUNT(*) FROM CUSTOMER";
 return jdbcTemplate.queryForObject(sql, Integer.class);      
}

Single column name

 public String findCustomerNameById(Long id) {

        String sql = "SELECT NAME FROM CUSTOMER WHERE ID = ?";

        return jdbcTemplate.queryForObject(
                sql, new Object[]{id}, String.class);

    }

How easy it is! Comment what you learned with the above examples. Your support will be appreciated.

adsense


Discover more from 9Mood

Subscribe to get the latest posts sent to your email.


Like it? Share with your friends!

-1
-1 points

What's Your Reaction?

Lol Lol
0
Lol
WTF WTF
0
WTF
Cute Cute
0
Cute
Love Love
0
Love
Vomit Vomit
0
Vomit
Cry Cry
0
Cry
Wow Wow
1
Wow
Fail Fail
0
Fail
Angry Angry
0
Angry
Rakshit Shah

Legend

Hey Moodies, Kem chho ? - Majama? (Yeah, You guessed Right! I am from Gujarat, India) 25, Computer Engineer, Foodie, Gamer, Coder and may be a Traveller . > If I can’t, who else will? < You can reach out me by “Rakshitshah94” on 9MOodQuoraMediumGithubInstagramsnapchattwitter, Even you can also google it to see me. I am everywhere, But I am not God. Feel free to text me.

0 Comments

Leave a Reply

Choose A Format
Story
Formatted Text with Embeds and Visuals
List
The Classic Internet Listicles
Ranked List
Upvote or downvote to decide the best list item
Open List
Submit your own item and vote up for the best submission
Countdown
The Classic Internet Countdowns
Meme
Upload your own images to make custom memes
Poll
Voting to make decisions or determine opinions
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Personality quiz
Series of questions that intends to reveal something about the personality
is avocado good for breakfast? Sustainability Tips for Living Green Daily Photos Taken At Right Moment