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!
More Posts related to Java,
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
More Posts:
- Microsoft Teams Error - You cannot add another work account to Teams at the moment - Teams
- Failed to install Android.apk on device 'emulator-5554': timeout - Android-Studio
- How to Use Command Prompt on a Mac? - MacOS
- Java: Convert Byte to Binary String Example - Java
- Mac OS X Stuck During Booting Gray Screen Logo and Spinner - Mac-OS-X
- How to take screenshot on Android - Android
- Install and Run Jupyter Notebook on Mac (macOS) - Python
- Customize Praise badge for Microsoft Teams with own images, values, brand - Microsoft