In this example, we will see how to perform simple CRUD operations using Spring Boot and JDBCTemplate class.
- Create Record
- Read All Record
- Read Record By Id
- Update Record
- Delete Record
Entity: Employee.java
public class Employee {
private int employeeId;
private String employeeName;
private int employeeSalary;
public Employee(int employeeId, String employeeName, int employeeSalary) {
this.employeeId = employeeId;
this.employeeName = employeeName;
this.employeeSalary = 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 int getEmployeeSalary() {
return employeeSalary;
}
public void setEmployeeSalary(int employeeSalary) {
this.employeeSalary = employeeSalary;
}
}
Repository Class: EmployeeRepository.java
import org.code2care.jdbctemplate.eg.jdbctemplateeg.entity.Employee;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class EmployeeRepository {
private JdbcTemplate jdbcTemplate;
public EmployeeRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate =jdbcTemplate;
}
private final String createQuerySQL ="INSERT INTO employee (employeeId, employeeName, employeeSalary) VALUES (?, ?, ?)";
private final String fetchAllQuerySQL = "SELECT employeeId, employeeName, employeeSalary FROM employee";
private final String fetchObjectQuerySQL = "SELECT employeeId, employeeName, employeeSalary FROM employee WHERE employeeId = ?";
private final String updateQuerySQL = "UPDATE employee SET employeeName = ?, employeeSalary = ? WHERE employeeId = ?";
private final String deleteQuerySQL = "DELETE FROM employee WHERE employeeId = ?";
// Create Example
public void createEmployee(Employee employee) {
jdbcTemplate.update(createQuerySQL, employee.getEmployeeId(), employee.getEmployeeName(), employee.getEmployeeSalary());
}
// Fetch all Example
public List<Employee> getAllEmployees() {
return jdbcTemplate.query(fetchAllQuerySQL, new BeanPropertyRowMapper<>(Employee.class));
}
// Retrieve an object by id Example
public Employee getEmployeeById(int employeeId) {
return jdbcTemplate.queryForObject(fetchObjectQuerySQL, new Object[]{employeeId}, new BeanPropertyRowMapper<>(Employee.class));
}
// Update example
public void updateEmployee(Employee employee) {
jdbcTemplate.update(updateQuerySQL, employee.getEmployeeName(), employee.getEmployeeSalary(), employee.getEmployeeId());
}
// Delete example
public void deleteEmployeeById(int employeeId) {
jdbcTemplate.update(deleteQuerySQL, employeeId);
}
}
CommandLineRunner
import org.code2care.jdbctemplate.eg.jdbctemplateeg.entity.Employee;
import org.code2care.jdbctemplate.eg.jdbctemplateeg.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
@SpringBootApplication
public class JdbctemplateCURDApplication implements CommandLineRunner {
@Autowired
private JdbcTemplate jdbcTemplate;
public static void main(String[] args) {
SpringApplication.run(JdbctemplateegApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
EmployeeRepository repo = new EmployeeRepository(jdbcTemplate);
// Create an employee
Employee newEmployee = new Employee(1, "John Smith", 5000);
repo.createEmployee(newEmployee);
// Read an employee by ID
Employee employee = repo.getEmployeeById(1);
System.out.println(employee);
// Update an employee's name and salary
employee.setEmployeeName("Jake Sally");
employee.setEmployeeSalary(6000);
repo.updateEmployee(employee);
// Delete an employee by ID
repo.deleteEmployeeById(1);
}
}
application.properties
spring.datasource.url=jdbc:mysql://localhost/jdbcTemplateDb
spring.datasource.username=root
spring.datasource.password=root-pwd
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
Spring Boot Starter Dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.14</version>
</dependency>
</dependencies>
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:
- Enable Native Dark Mode in Notepad++ - NotepadPlusPlus
- How to turn on channel notifications for Microsoft Teams - Teams
- Android Studio Ctrl Shift o auto import not working - Android
- List of 32 CSS cursors web developers must know about - CSS
- Android Studio Change SDK Path - Android
- Implementing Bubble Sort Algorithm using Java Program - Java
- How to check file permissions for your file using Linux/Unix/macOS Terminal Command - Linux
- How to change bash terminal prompt string and color - Linux