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

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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

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

  • Issue and Present Verifiable Credentials With Spring Boot and Android
  • How to Practice TDD With Kotlin
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • A Modern Stack for Building Scalable Systems
  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
19.7K 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.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: