The JdbcTemplate class from the Spring Framework provides a simplified way to work with the Java JDBC API. It provides a higher-level abstraction over the raw JDBC API. You can quickly and easily create Java applications with less boilerplate code and have your focus on your application logic.
Below are a few scenarios where you might want to consider using JdbcTemplate:
- If you want more control over the SQL that is executed.
- If are working with a legacy database that does not support Hibernate or JPA.
- Reduce latency by reducing the overhead of ORM frameworks.
- When you need to perform simple JDBC operations in your application.
- If your project needs to perform bulk insert/update/delete operations.
- If you are working with a small to medium-sized (or POC) application with relatively simple database requirements.
- If you want to write SQL that is specific to your database platform.
Querying Examples with Spring Boot 3 + JDBCTemplate
Please follow this tutorial for setting up your Project with JDBC Template: https://code2care.org/java/spring-boot-setting-up-jdbc-template-mysql-tutorial
Let's consider that we have an Employee table in our database and the corresponding PoJo in our Project.
Table SQL:CREATE TABLE `employee` (
`employeeId` int(5) NOT NULL,
`employeeName` varchar(255) NOT NULL,
`employeeDateOfBirth` date NOT NULL,
`employeeDepartment` varchar(255) NOT NULL,
`employeeJoiningDate` date NOT NULL,
`employeeSalary` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
COMMIT;
package org.code2care.jdbctemplate.eg.entities;
import java.time.LocalDate;
public class Employee {
private int employeeId;
private String employeeName;
private LocalDate employeeDateOfBirth;
private String employeeDepartment;
private LocalDate employeeJoiningDate;
private String employeeAddress;
private int employeeSalary;
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public LocalDate getEmployeeDateOfBirth() {
return employeeDateOfBirth;
}
public void setEmployeeDateOfBirth(LocalDate employeeDateOfBirth) {
this.employeeDateOfBirth = employeeDateOfBirth;
}
public String getEmployeeDepartment() {
return employeeDepartment;
}
public void setEmployeeDepartment(String employeeDepartment) {
this.employeeDepartment = employeeDepartment;
}
public LocalDate getEmployeeJoiningDate() {
return employeeJoiningDate;
}
public void setEmployeeJoiningDate(LocalDate employeeJoiningDate) {
this.employeeJoiningDate = employeeJoiningDate;
}
public String getEmployeeAddress() {
return employeeAddress;
}
public void setEmployeeAddress(String employeeAddress) {
this.employeeAddress = employeeAddress;
}
public int getEmployeeSalary() {
return employeeSalary;
}
public void setEmployeeSalary(int employeeSalary) {
this.employeeSalary = employeeSalary;
}
@Override
public String toString() {
return "Employee{" +
"employeeId=" + employeeId +
", employeeName='" + employeeName + '\'' +
", employeeDateOfBirth=" + employeeDateOfBirth +
", employeeDepartment='" + employeeDepartment + '\'' +
", employeeJoiningDate=" + employeeJoiningDate +
", employeeAddress='" + employeeAddress + '\'' +
", employeeSalary=" + employeeSalary +
'}';
}
}
Select * Query Example:
Output:import org.code2care.jdbctemplate.eg.jdbctemplateeg.entities.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import java.util.List; @Component public class JDBCTemplateRunner implements CommandLineRunner { @Autowired private JdbcTemplate jdbcTemplate; private static String selectQuery = "Select * from employee"; public List<Employee> getAllEmployees() { List<Employee> employeeList = jdbcTemplate.query(selectQuery, new BeanPropertyRowMapper<>(Employee.class)); return employeeList; } @Override public void run(String... args) throws Exception { System.out.println(getAllEmployees()); } }
[ Employee { employeeId=101, employeeName='Sam', employeeDateOfBirth=2000-04-04, employeeDepartment='IT', employeeJoiningDate=2022-04-01, employeeAddress='null', employeeSalary=24000}, Employee{ employeeId=201, employeeName='Alan', employeeDateOfBirth=1998-04-04, employeeDepartment='IT', employeeJoiningDate=2010-02-01, employeeAddress='null', employeeSalary=55000} ]
-
Query for Single Row/Object using where clause
Output:@Component public class JDBCTemplateRunner implements CommandLineRunner { @Autowired private JdbcTemplate jdbcTemplate; private static String selectQuery = "Select * from employee where employeeName='Sam'"; public Employee getEmployee() { Employee employee = jdbcTemplate.queryForObject(selectQuery,new BeanPropertyRowMapper<>(Employee.class)); return employee; } @Override public void run(String... args) throws Exception { System.out.println(getEmployee()); } }
Employee { employeeId=101, employeeName='Sam', employeeDateOfBirth=2000-04-04, employeeDepartment='IT', employeeJoiningDate=2022-04-01, employeeAddress='null', employeeSalary=24000}
Get the count of a table
Output: 2@Component public class JDBCTemplateRunner implements CommandLineRunner { @Autowired private JdbcTemplate jdbcTemplate; private static String selectQuery = "Select count(*) from employee"; public int getEmployee() { int empCount = jdbcTemplate.queryForObject(selectQuery,Integer.class); return empCount; } @Override public void run(String... args) throws Exception { System.out.println(getEmployee()); } }
Insert in table query
Output:@Autowired private JdbcTemplate jdbcTemplate; private static String insertQuery = "INSERT INTO `employee` " + "(`employeeId`, `employeeName`, " + "`employeeDateOfBirth`, `" + "employeeDepartment`, `employeeJoiningDate`, " + "`employeeSalary`) " + "" + "VALUES ('301', 'Mike', '1996-01-01', 'Finance', '2012-01-01', '75000');"; public int insertEmployee() { int empCount = jdbcTemplate.update(insertQuery); return empCount; } @Override public void run(String... args) throws Exception { System.out.println(insertEmployee()); }
1
Update in table query
@Component public class JDBCTemplateRunner implements CommandLineRunner { @Autowired private JdbcTemplate jdbcTemplate; private static String updateQuery = "UPDATE employee \n" + "SET employeeName=?\n" + "WHERE employeeId=?;"; public int updateEmployee() { int empCount = jdbcTemplate.update(updateQuery,"Alex",101); return empCount; } @Override public void run(String... args) throws Exception { System.out.println(updateEmployee()); //1 = Success } }
Delete Query
Example:Facing issues? Have Questions? Post them here! I am happy to answer!
Author Info:Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
More Posts related to Java,- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
More Posts:- How to Add Git Bash Option to Windows Terminal List - Git
- How to export bookmarks from Google Chrome Browser - Chrome
- How to Open Private Browsing (Incognito Mode) in Safari on Mac - MacOS
- How to Align Text using Notepad++ - NotepadPlusPlus
- Program 9: Divide Two Numbers - 1000+ Python Programs - Python-Programs
- How to take Screenshot on Android device - Android
- How to add duration to Android Toast makeText method - Android
- [Java] Read a File with UTF-8 Encoding - Java