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>
Have Questions? Post them here!
- Create a Zip file using Java Code programmatically
- Eclipse : A java Runtime Environment (JRE) or Java Development kit (JDK) must be available
- How to Sort a LinkedList in Java
- Loading class com.mysql.jdbc.Driver. This is deprecated. The new driver class is com.mysql.cj.jdbc.Driver
- How to declare and initialize Array in Java Programming
- [Fix] java: integer number too large compilation error
- Java JDBC Connection with MySQL Driver in VS Code + Troubleshooting
- Reading .xls and .xlsx Excel file using Apache POI Java Library
- IntelliJ: Error: Could not find or load main class, java.lang.ClassNotFoundException
- How to get Client IP address using Java Code Example
- Truncate table using Java JDBC Example
- Struts 2 : There is no Action mapped for namespace [/] and action name [form] associated with context path [/proj]
- How to get file path in Idea IntelliJ IDE
- Java Generics explained with simple definition and examples
- Java SE 8 Update 301 available with various bug fixes and security improvements
- Java: Collect Stream as ArrayList or LinkedList
- Java JDBC Connection with PostgreSQL Driver Example
- How to check if Java main thread is alive
- How to fix Java nio NoSuchFileException wile reading a file
- Java 8+ get Day of the Week Examples with LocalDateTime, DateTime, ZonalDateTime and Instant classes
- Ways to Convert Integer or int to Long in Java
- [Java] How to throws Exception using Functional Interface and Lambda code
- [Fix] Spring Boot: mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
- Java: The value of the local variable string is not used
- Java JDBC: Insert Java 8 LocalDate and Time using PreparedStatement
- Microsoft Teams: Delay in sending and receiving messages - TM495986 - Teams
- How to Change Mouse Wheel Scroll Direction on Mac - MacOS
- Convert Float to String in Python - Python
- Android : Remove ListView Separator/divider programmatically or using xml property - Android
- Calculate Area of ellipse - C-Program
- How to Copy files from Docker Container to Host System - Docker
- Efficient way to perform HTTP cURL GET/POST Requests with Payload - cURL
- Create a Zip file using Java Code programmatically - Java