📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Table of Contents
- Introduction to CRUD Operations
- Performing CRUD Operations using In-Memory Object
- Performing CRUD Operations using JDBC with MySQL Database
- Conclusion
1. Introduction to CRUD Operations
CRUD operations are the four basic functions of persistent storage. They are:
- Create: Add new records.
- Read: Retrieve records.
- Update: Modify existing records.
- Delete: Remove records.
These operations are essential in any application that deals with data storage.
2. Performing CRUD Operations using In-Memory Object
Let's start by performing CRUD operations using a simple in-memory object. We'll use a list to store our data.
Create an Employee Class
package com.example.crud; public class Employee { private int id; private String name; private String email; private String department; public Employee(int id, String name, String email, String department) { this.id = id; this.name = name; this.email = email; this.department = department; } // Getters and setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } @Override public String toString() { return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", email='" + email + '\'' + ", department='" + department + '\'' + '}'; } }
Create an In-Memory CRUD Service
package com.example.crud; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class EmployeeService { private List<Employee> employees = new ArrayList<>(); // Create public void addEmployee(Employee employee) { employees.add(employee); } // Read public List<Employee> getAllEmployees() { return employees; } public Optional<Employee> getEmployeeById(int id) { return employees.stream().filter(emp -> emp.getId() == id).findFirst(); } // Update public void updateEmployee(Employee updatedEmployee) { getEmployeeById(updatedEmployee.getId()).ifPresent(employee -> { employee.setName(updatedEmployee.getName()); employee.setEmail(updatedEmployee.getEmail()); employee.setDepartment(updatedEmployee.getDepartment()); }); } // Delete public void deleteEmployee(int id) { employees.removeIf(emp -> emp.getId() == id); } }
Test the In-Memory CRUD Operations
package com.example.crud; public class TestEmployeeService { public static void main(String[] args) { EmployeeService employeeService = new EmployeeService(); // Create employees Employee emp1 = new Employee(1, "Ravi Kumar", "ravi.kumar@example.com", "IT"); Employee emp2 = new Employee(2, "Sita Sharma", "sita.sharma@example.com", "Finance"); employeeService.addEmployee(emp1); employeeService.addEmployee(emp2); // Read employees System.out.println("Employees after creation:"); employeeService.getAllEmployees().forEach(System.out::println); // Update employee Employee updatedEmp1 = new Employee(1, "Ravi Kumar Singh", "ravi.singh@example.com", "IT"); employeeService.updateEmployee(updatedEmp1); // Read employees System.out.println("Employees after update:"); employeeService.getAllEmployees().forEach(System.out::println); // Delete employee employeeService.deleteEmployee(2); // Read employees System.out.println("Employees after deletion:"); employeeService.getAllEmployees().forEach(System.out::println); } }
3. Performing CRUD Operations using JDBC with MySQL Database
Next, let's perform the same CRUD operations using JDBC with a MySQL database.
Database Setup
First, create a database and a table in MySQL.
CREATE DATABASE test_db; USE test_db; CREATE TABLE employees ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, email VARCHAR(50) NOT NULL, department VARCHAR(50) NOT NULL );
Create JDBC Utility Class
package com.example.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class JDBCUtils { private static final String URL = "jdbc:mysql://localhost:3306/test_db?useSSL=false"; private static final String USER = "root"; private static final String PASSWORD = "root"; public static Connection getConnection() throws SQLException { return DriverManager.getConnection(URL, USER, PASSWORD); } public static void printSQLException(SQLException ex) { for (Throwable e : ex) { if (e instanceof SQLException) { e.printStackTrace(System.err); System.err.println("SQLState: " + ((SQLException) e).getSQLState()); System.err.println("Error Code: " + ((SQLException) e).getErrorCode()); System.err.println("Message: " + e.getMessage()); Throwable t = ex.getCause(); while (t != null) { System.out.println("Cause: " + t); t = t.getCause(); } } } } }
CRUD Operations using JDBC
Create
package com.example.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class InsertEmployee { private static final String INSERT_EMPLOYEES_SQL = "INSERT INTO employees (name, email, department) VALUES (?, ?, ?);"; public void insertRecord(String name, String email, String department) throws SQLException { try (Connection connection = JDBCUtils.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(INSERT_EMPLOYEES_SQL)) { preparedStatement.setString(1, name); preparedStatement.setString(2, email); preparedStatement.setString(3, department); preparedStatement.executeUpdate(); } catch (SQLException e) { JDBCUtils.printSQLException(e); } } }
Read
package com.example.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class SelectEmployees { private static final String SELECT_ALL_EMPLOYEES = "SELECT * FROM employees;"; public void selectAllRecords() throws SQLException { try (Connection connection = JDBCUtils.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ALL_EMPLOYEES)) { ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); String department = rs.getString("department"); System.out.println(id + ", " + name + ", " + email + ", " + department); } } catch (SQLException e) { JDBCUtils.printSQLException(e); } } }
Update
package com.example.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class UpdateEmployee { private static final String UPDATE_EMPLOYEES_SQL = "UPDATE employees SET name = ?, email = ?, department = ? WHERE id = ?;"; public void updateRecord(int id, String name, String email, String department) throws SQLException { try (Connection connection = JDBCUtils.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_EMPLOYEES_SQL)) { preparedStatement.setString(1, name); preparedStatement.setString(2, email); preparedStatement.setString(3, department); preparedStatement.setInt(4, id); preparedStatement.executeUpdate(); } catch (SQLException e) { JDBCUtils.printSQLException(e); } } }
Delete
package com.example.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class DeleteEmployee { private static final String DELETE_EMPLOYEES_SQL = "DELETE FROM employees WHERE id = ?;"; public void deleteRecord(int id) throws SQLException { try (Connection connection = JDBCUtils.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(DELETE_EMPLOYEES_SQL)) { preparedStatement.setInt(1, id); preparedStatement.executeUpdate(); } catch (SQLException e) { JDBCUtils.printSQLException(e); } } }
Test CRUD Operations using JDBC
package com.example.jdbc; import java.sql.SQLException; public class TestCRUDOperations { public static void main(String[] args) { InsertEmployee insertEmployee = new InsertEmployee(); SelectEmployees selectEmployees = new SelectEmployees(); UpdateEmployee updateEmployee = new UpdateEmployee(); DeleteEmployee deleteEmployee = new DeleteEmployee(); try { // Insert records insertEmployee.insertRecord("Ravi Kumar", "ravi .kumar@example.com", "IT"); insertEmployee.insertRecord("Sita Sharma", "sita.sharma@example.com", "Finance"); insertEmployee.insertRecord("Rahul Jain", "rahul.jain@example.com", "HR"); // Read records System.out.println("Employees after insertion:"); selectEmployees.selectAllRecords(); // Update record updateEmployee.updateRecord(1, "Ravi Kumar Singh", "ravi.singh@example.com", "IT"); // Read records System.out.println("Employees after updating record with ID 1:"); selectEmployees.selectAllRecords(); // Delete record deleteEmployee.deleteRecord(3); // Read records System.out.println("Employees after deleting record with ID 3:"); selectEmployees.selectAllRecords(); } catch (SQLException e) { e.printStackTrace(); } } }
Conclusion
In this tutorial, we covered the basics of CRUD operations and demonstrated how to perform these operations using an in-memory object and JDBC with a MySQL database. Following these examples, you can understand how to create, read, update, and delete records in Java applications using different storage mechanisms.
Comments
Post a Comment
Leave Comment