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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  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.

Juan Manuel Kelsy Romero user avatar by
Juan Manuel Kelsy Romero
·
May. 14, 19 · Tutorial
Like (3)
Save
Tweet
Share
17.72K 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.

Popular on DZone

  • Silver Bullet or False Panacea? 3 Questions for Data Contracts
  • Best Practices for Writing Clean and Maintainable Code
  • Core Machine Learning Metrics
  • DevOps Roadmap for 2022

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: