Sunday, 10 February 2019

Spring + JdbcTemplate + Custom RowMapper example | Spring JDBC tutorial

🚀 Boost Your Java Career!

Don't miss out on the latest Spring tutorials and tech deep dives. Join our community today!

SUBSCRIBE TO RAM N JAVA

Taking Control with Custom RowMappers in Spring JDBC

When you move beyond simple database queries, you often find that automatic mapping isn't enough. That's where the Custom RowMapper comes in. In this guide, we'll break down how to bridge the gap between your SQL tables and complex Java objects with ease.

What is a Custom RowMapper?

A RowMapper is a specific interface used by Spring's JdbcTemplate to map rows of a ResultSet on a per-row basis. While Spring provides built-in tools like BeanPropertyRowMapper, a Custom RowMapper gives you 100% control over how each column is mapped to your Java Bean fields.

Why Use a Custom Mapper?

As a beginner, you might wonder why you should write extra code. Here are three big reasons:

  • Complex Data Types: Handle logic that requires data conversion or formatting during mapping.
  • Nested Objects: Easily map flat SQL results into complex Java objects with nested dependencies.
  • Performance: It is generally faster than reflection-based mappers because you are writing the direct assignment code.

The Implementation Steps

Implementing it is simple! You just need to create a class that implements RowMapper<T> and override the mapRow method. Inside that method, you use the ResultSet object to get your data and set it into your object. Then, just pass this mapper into your jdbcTemplate.query() call!


More Tech Insights from Ram N Java

Enjoyed this tutorial? Expand your knowledge with these other popular videos from my channel:


Click here to watch on Youtube:
https://www.youtube.com/watch?v=7kZUKT0MvMg&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge:
Spring + JdbcTemplate + Custom RowMapper example | Spring JDBC tutorial

Employee.sql

CREATE DATABASE org_db;


CREATE TABLE `employee` (
  `EMPLOYEE_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `NAME` VARCHAR(100) NOT NULL,
  `AGE` INT(10) NOT NULL,
  `SALARY` INT(10) DEFAULT NULL,
  PRIMARY KEY (`EMPLOYEE_ID`)
) ENGINE=INNODB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ram.core</groupId>
    <artifactId>SpringDemo</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringDemo</name>
    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>5.0.5.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- Spring 5 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- MySQL database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

    </dependencies>

</project>

Employee.java

package com.ram.employee.model;

public class Employee
{
    private int employeeId;
    private String name;
    private int age;
    private int salary;

    public int getEmployeeId()
    {
        return employeeId;
    }

    public void setEmployeeId(int employeeId)
    {
        this.employeeId = employeeId;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }

    public int getSalary()
    {
        return salary;
    }

    public void setSalary(int salary)
    {
        this.salary = salary;
    }

    @Override
    public String toString()
    {
        return "Employee [employeeId=" + employeeId + ", name=" + name
                + ", age=" + age + ", salary=" + salary + "]";
    }

}

EmployeeRowMapper.java

package com.ram.employee.dao.mapper;

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

import org.springframework.jdbc.core.RowMapper;

import com.ram.employee.model.Employee;

public class EmployeeRowMapper implements RowMapper<Employee>
{

    public Employee mapRow(ResultSet rs, int rowNum) throws SQLException
    {
        Employee employee = new Employee();
        employee.setEmployeeId(rs.getInt("EMPLOYEE_ID"));
        employee.setName(rs.getString("NAME"));
        employee.setAge(rs.getInt("AGE"));
        employee.setSalary(rs.getInt("SALARY"));
        return employee;
    }

}

EmployeeDAO.java

package com.ram.employee.dao;

import com.ram.employee.model.Employee;

public interface EmployeeDAO
{
    public Employee findByEmployeeId(int employeeId);
}

EmployeeDAOImpl.java

package com.ram.employee.dao.impl;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.ram.employee.dao.EmployeeDAO;
import com.ram.employee.dao.mapper.EmployeeRowMapper;
import com.ram.employee.model.Employee;

public class EmployeeDAOImpl
        extends JdbcDaoSupport implements EmployeeDAO
{

    public Employee findByEmployeeId(int employeeId)
    {
        String sql = "SELECT * FROM EMPLOYEE WHERE EMPLOYEE_ID = ?";
       
        Employee employee = (Employee)getJdbcTemplate().queryForObject(
                sql, new Object[] { employeeId }, new EmployeeRowMapper());
           
        return employee;
       
    }

   
}

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">


    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/org_db" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <bean id="employeeDAO" class="com.ram.employee.dao.impl.EmployeeDAOImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>
   
</beans>

App.java

package com.ram.core;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ram.employee.dao.EmployeeDAO;
import com.ram.employee.model.Employee;

public class App
{
    public static void main(String[] args)
    {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");

        EmployeeDAO employeeDAO = (EmployeeDAO) context
                .getBean("employeeDAO");
        Employee employee = employeeDAO.findByEmployeeId(1);
        System.out.println("employee = " + employee);
    }
}

Output:

Feb 01, 2019 10:17:39 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@35d176f7: startup date [Fri Feb 01 10:17:39 IST 2019]; root of context hierarchy
Feb 01, 2019 10:17:39 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Feb 01, 2019 10:17:40 AM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Fri Feb 01 10:17:53 IST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
employee = Employee [employeeId=1, name=Peter, age=28, salary=80000]

Click the below link to download the code:
https://sites.google.com/site/javaspringram2019/java_spring_2019/SpringDemo_RowMapper.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java_Spring_2019/tree/master/Spring_2019/SpringDemo_RowMapper

Bitbucket Link:
https://bitbucket.org/ramram43210/java_spring_2019/src/f6e436d66d082f1d909211259e21badb13bac610/Spring_2019/SpringDemo_RowMapper/?at=master

See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • No comments:

    Post a Comment

    Tutorials