DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Spring Boot: How To Use Java Persistence Query Language (JPQL)
  • How To Build Web Service Using Spring Boot 2.x
  • How To Build Self-Hosted RSS Feed Reader Using Spring Boot and Redis

Trending

  • Prompt Injection Is Real, So I Built a Python Firewall for LLM Pipelines
  • Mastering Fluent Bit: Beginners' Guide for Contributing to Our CNCF Project Website
  • Migrate a Hardcoded LangGraph Agent to LaunchDarkly AI Configs in 20 Minutes
  • Stop Debugging Glue Jobs Manually: Building an Agentic Observability Layer for Data Pipelines
  1. DZone
  2. Coding
  3. Frameworks
  4. Native Queries With Spring Boot and NamedParameterJdbcTemplate

Native Queries With Spring Boot and NamedParameterJdbcTemplate

Let's see an example of how to use NamedParameterJdbcTemplate.

By 
Juan Manuel Kelsy Romero user avatar
Juan Manuel Kelsy Romero
·
May. 14, 19 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
20.1K Views

Join the DZone community and get the full member experience.

Join For Free

Do you need to run a native query with Spring Boot? Should you consult a database of a legacy application? Do you feel that if you execute a native query you save the mapping of many tables in your database?

Well, for these cases, my favorite way is to use NamedParameterJdbcTemplate. Next, we will see an example of how to use it. In our case, we must obtain the quantity of orders from a given customer.

First, we must define the POJO (DTO) that will obtain the result of the query:

public class NativeQueryDTO {
    private String name;
    private int orderCount;
...
    //Getters - Setters   
}

Then we must create the repository, which contains the method that returns the required information:

@Component
public class NativeRepository {
    @Autowired 
    private NamedParameterJdbcTemplate jdbcTemplate;

    public NativeQueryDTO countCustomerOrder(Long id){        
        MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue("customerId", id);

        String sql = " select c.name, count(o) as orderCount  "
                   + " from customers c, orders o "
                   + " where c.id = o.customer_id and c.id = :customerId "
                   + " group by c.name ";

        return (NativeQueryDTO)jdbcTemplate.queryForObject(
            sql, parameters, BeanPropertyRowMapper.newInstance(NativeQueryDTO.class));  
    }
}

The previous code uses the queryForObject method that executes the query, and the necessary parameters are passed with the object of type MapSqlParameterSource. To obtain a correct mapping as a third parameter, we must send a BeanPropertyRowMapper with the class mapping. Because we are using BeanPropertyRowMapper, we do not need to implement a RowMapper.

Finally, in the official documentation of Spring, they recommend the implementation of a customized RowMapper in case of needing better performance.

public class NativeQueryDTOMapper implements RowMapper<NativeQueryDTO> {
    @Override
    public NativeQueryDTO mapRow(ResultSet rs, int rowNum) throws SQLException {
        NativeQueryDTO dto = new NativeQueryDTO();
        dto.setName(rs.getString("name"));
        dto.setOrderCount(rs.getInt("orderCount"));
        return dto;
    }  
}

Then use it as follows:

return (NativeQueryDTO)jdbcTemplate.queryForObject(
            sql, parameters, new NativeQueryDTOMapper());  

We have seen that it is very easy to use native queries with Spring Boot, and I hope that this example was helpful. Until next time!

Spring Framework Database Spring Boot

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Spring Boot: How To Use Java Persistence Query Language (JPQL)
  • How To Build Web Service Using Spring Boot 2.x
  • How To Build Self-Hosted RSS Feed Reader Using Spring Boot and Redis

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook