CRUD stands for Create, Read, Update, and Delete. These are considered as the basic operations that can be performed on a database or data storage system.
Let's take a look at how to perform these operations with Spring Boot + plain JDBC
Step 1: Database Configuration
We will be using MySQL database, you may follow the below link and choose the configuration for wide variety of RDS or NoSQL databases.
applications.propertiesspring.datasource.url=jdbc:mysql://localhost/jdbctest
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
pom.xml dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-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>
Now let us create a database table called insurance_companies,
Step 2: Setting up our Pojo for the CRUD Examples
package org.code2care.springboot.jdbctutorial;
public class InsuranceCompany {
private String companyName;
private int headcount2020;
private String headOfficeLocation;
public InsuranceCompany() {
}
public InsuranceCompany(String companyName, int headcount2020, String headOfficeLocation) {
this.companyName = companyName;
this.headcount2020 = headcount2020;
this.headOfficeLocation = headOfficeLocation;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public int getHeadcount2020() {
return headcount2020;
}
public void setHeadcount2020(int headcount2020) {
this.headcount2020 = headcount2020;
}
public String getHeadOfficeLocation() {
return headOfficeLocation;
}
public void setHeadOfficeLocation(String headOfficeLocation) {
this.headOfficeLocation = headOfficeLocation;
}
@Override
public String toString() {
return "InsuranceCompany{" +
"companyName='" + companyName + '\'' +
", headcount2020=" + headcount2020 +
", headOfficeLocation='" + headOfficeLocation + '\'' +
'}';
}
}
Step 3: Methods for all CRUD operations
Create Operation
-
Example: Insert a single record using Prepared Statement
String sql = "INSERT INTO insurance_companies (company_name, headcount_2020, head_office_location) VALUES (?, ?, ?)";
jdbcTemplate.update(sql, "MetLife", 49000, "New York");
Example: Insert multiple records using Batch Update
package org.code2care.springboot.jdbctutorial;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class InsuranceCompanyRunner implements CommandLineRunner {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void run(String... args) throws Exception {
List<InsuranceCompanies> companies = new ArrayList<>();
companies.add(new InsuranceCompanies("MetLife", 49000, "New York"));
companies.add(new InsuranceCompanies("Prudential Financial", 50527, "Newark"));
companies.add(new InsuranceCompanies("New York Life Insurance", 11902, "New York"));
companies.add(new InsuranceCompanies("Aflac", 11128, "Columbus"));
companies.add(new InsuranceCompanies("Liberty Mutual", 45000, "Boston"));
// Prepare the SQL insert statement
String sql = "INSERT INTO insurance_companies (company_name, headcount_2020, head_office_location) VALUES (?, ?, ?)";
List<Object[]> batchArgs = new ArrayList<>();
for (InsuranceCompanies company : companies) {
Object[] params = {company.getCompanyName(), company.getHeadcount2020(), company.getHeadOfficeLocation()};
batchArgs.add(params);
}
jdbcTemplate.batchUpdate(sql, batchArgs); //batch Update
}
}

Read Operation using Prepared Statement
package org.code2care.springboot.jdbctutorial;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class InsuranceCompanyRunner implements CommandLineRunner {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void run(String... args) throws Exception {
String findQuery = "SELECT * FROM insurance_companies WHERE company_name = ?";
List<InsuranceCompanies> companies = jdbcTemplate.query(
findQuery,
new Object[]{"MetLife"},
(rs, rowNum) -> new InsuranceCompanies(
rs.getString("company_name"),
rs.getInt("headcount_2020"),
rs.getString("head_office_location")
)
);
for (InsuranceCompanies company : companies) {
System.out.println(company.toString());
}
}
}
Update Operation with Prepared Statement
String updateQuery = "UPDATE insurance_companies SET headcount_2020 = ? WHERE company_name = ?";
int rowsAffected = jdbcTemplate.update(updateQuery, 11129, "Alfac");
if (rowsAffected > 0) {
System.out.println("Record updated successfully.");
} else {
System.out.println("No record found with Company Name Alfac.");
}
Delete Operation with Prepared Statement
String deleteSQL = "DELETE FROM insurance_companies WHERE company_name = ?";
int rowsAffected = jdbcTemplate.update(deleteSQL, "Aflac");
if (rowsAffected > 0) {
System.out.println("Record deleted successfully.");
} else {
System.out.println("No record found with Company Name Aflac.");
}
Step 4: Complete CRUD Code in One Class
package org.code2care.springboot.jdbctutorial;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class InsuranceCRUD implements CommandLineRunner {
@Autowired
private final JdbcTemplate jdbcTemplate;
public InsuranceCRUD(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public void run(String... args) throws Exception {
// 1. Create
String sql = "INSERT INTO insurance_companies (company_name, headcount_2020, head_office_location) VALUES (?, ?, ?)";
jdbcTemplate.update(sql, "MetLife", 49000, "New York");
System.out.println("Created Db entry for company MetLife");
// 2. Read
String findQuery = "SELECT * FROM insurance_companies WHERE company_name = ?";
List<InsuranceCompanies> companies = jdbcTemplate.query(
findQuery,
new Object[]{"MetLife"},
(rs, rowNum) -> new InsuranceCompanies(
rs.getString("company_name"),
rs.getInt("headcount_2020"),
rs.getString("head_office_location")
)
);
for (InsuranceCompanies company : companies) {
System.out.println("Read: "+ company.toString());
}
// 3. Update
String updateQuery = "UPDATE insurance_companies SET headcount_2020 = ? WHERE company_name = ?";
int rowsAffected = jdbcTemplate.update(updateQuery, 50000, "MetLife");
if (rowsAffected > 0) {
System.out.println("Updated record successfully.");
} else {
System.out.println("No record found with Company Name MetLife.");
}
// 4. Delete
String deleteSQL = "DELETE FROM insurance_companies WHERE company_name = ?";
rowsAffected = jdbcTemplate.update(deleteSQL, "MetLife");
if (rowsAffected > 0) {
System.out.println("Deleted record successfully.");
} else {
System.out.println("No record found with Company Name MetLife.");
}
}
}
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
- List of Java JDBC Database Driver Jars, Classes and URLs Details - Java
- How to copy file name and path to clipboard in Notepad++ - NotepadPlusPlus
- The default username and password for RabbitMQ - HowTos
- Eclipse Error The JVM Shared Library JavaVirtualMachines does not contain the JNI_CreateJavaVM symbol - Eclipse
- How to see HTTP Request Response Headers in Google Chrome Browser - Chrome
- Java 8 foreach loop code examples - Java
- No Android device found : Android File Transfer App Mac OS X - Android
- How to Open and Use Microsoft Edge Console - Microsoft