In this article, we will build a simple Java Inventory Management application that includes full CRUD (Create, Read, Update, Delete) functionality. We will use Java and MySQL for database operations. The application will follow a class-based design pattern with detailed comments to explain each part of the code.
Before we start, ensure you have the following installed on your system:
- JDK (Java Development Kit)
- MySQL Server
- MySQL JDBC Driver
2. Setting Up the MySQL Database
First, we need to set up our MySQL database. Open your MySQL client and run the following SQL commands:
CREATE DATABASE inventory_db;
USE inventory_db;
CREATE TABLE inventory (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
quantity INT NOT NULL,
price DOUBLE NOT NULL
);
3. Creating the Java Project
Create a new Java project in your favorite IDE and add the MySQL JDBC Driver to your project’s classpath.
4. Creating the Database Connection Class
We will create a DatabaseConnection
class to manage the connection to our MySQL database.
Follow Us
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Class to manage database connections
public class DatabaseConnection {
// Database URL, username, and password
private static final String URL = "jdbc:mysql://localhost:3306/inventory_db";
private static final String USER = "root";
private static final String PASSWORD = "password";
// Method to establish and return the database connection
public static Connection getConnection() {
Connection connection = null; // Initialize connection as null
try {
// Try to establish a connection using the provided URL, username, and password
connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException e) {
e.printStackTrace(); // Print stack trace if connection fails
}
return connection; // Return the established connection
}
}
5. Creating the Inventory Item Class
This class will represent an item in the inventory.
// Class representing an item in the inventory
public class InventoryItem {
// Fields representing item properties
private int id;
private String name;
private int quantity;
private double price;
// Constructor to initialize all fields
public InventoryItem(int id, String name, int quantity, double price) {
this.id = id;
this.name = name;
this.quantity = quantity;
this.price = price;
}
// Getter for id
public int getId() {
return id;
}
// Setter for id
public void setId(int id) {
this.id = id;
}
// Getter for name
public String getName() {
return name;
}
// Setter for name
public void setName(String name) {
this.name = name;
}
// Getter for quantity
public int getQuantity() {
return quantity;
}
// Setter for quantity
public void setQuantity(int quantity) {
this.quantity = quantity;
}
// Getter for price
public double getPrice() {
return price;
}
// Setter for price
public void setPrice(double price) {
this.price = price;
}
// Override toString method to return item details as a string
@Override
public String toString() {
return "InventoryItem{" +
"id=" + id +
", name='" + name + '\'' +
", quantity=" + quantity +
", price=" + price +
'}';
}
}
6. Implementing the CRUD Operations
We will create an InventoryDAO
class that will handle the CRUD operations.
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
// Data Access Object class for inventory operations
public class InventoryDAO {
private Connection connection; // Connection object to interact with the database
// Constructor to establish connection using DatabaseConnection class
public InventoryDAO() {
connection = DatabaseConnection.getConnection();
}
// Method to add a new inventory item
public void addItem(InventoryItem item) {
String query = "INSERT INTO inventory (name, quantity, price) VALUES (?, ?, ?)"; // SQL query to insert item
try (PreparedStatement stmt = connection.prepareStatement(query)) {
stmt.setString(1, item.getName()); // Set item name
stmt.setInt(2, item.getQuantity()); // Set item quantity
stmt.setDouble(3, item.getPrice()); // Set item price
stmt.executeUpdate(); // Execute the update
} catch (SQLException e) {
e.printStackTrace(); // Print stack trace if SQL operation fails
}
}
// Method to retrieve all inventory items
public List<InventoryItem> getAllItems() {
List<InventoryItem> items = new ArrayList<>(); // List to store retrieved items
String query = "SELECT * FROM inventory"; // SQL query to select all items
try (Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query)) { // Execute the query
while (rs.next()) { // Iterate through the result set
InventoryItem item = new InventoryItem(
rs.getInt("id"), // Retrieve id
rs.getString("name"), // Retrieve name
rs.getInt("quantity"), // Retrieve quantity
rs.getDouble("price") // Retrieve price
);
items.add(item); // Add item to the list
}
} catch (SQLException e) {
e.printStackTrace(); // Print stack trace if SQL operation fails
}
return items; // Return the list of items
}
// Method to update an existing inventory item
public void updateItem(InventoryItem item) {
String query = "UPDATE inventory SET name = ?, quantity = ?, price = ? WHERE id = ?"; // SQL query to update item
try (PreparedStatement stmt = connection.prepareStatement(query)) {
stmt.setString(1, item.getName()); // Set updated name
stmt.setInt(2, item.getQuantity()); // Set updated quantity
stmt.setDouble(3, item.getPrice()); // Set updated price
stmt.setInt(4, item.getId()); // Set item id to update
stmt.executeUpdate(); // Execute the update
} catch (SQLException e) {
e.printStackTrace(); // Print stack trace if SQL operation fails
}
}
// Method to delete an inventory item by id
public void deleteItem(int id) {
String query = "DELETE FROM inventory WHERE id = ?"; // SQL query to delete item
try (PreparedStatement stmt = connection.prepareStatement(query)) {
stmt.setInt(1, id); // Set id of item to delete
stmt.executeUpdate(); // Execute the update
} catch (SQLException e) {
e.printStackTrace(); // Print stack trace if SQL operation fails
}
}
}
7. Creating the Main Application Class
Finally, we create a Main
class to interact with our InventoryDAO
and perform CRUD operations.
import java.util.List;
// Main class to demonstrate CRUD operations
public class Main {
public static void main(String[] args) {
InventoryDAO inventoryDAO = new InventoryDAO(); // Create instance of InventoryDAO
// Add new items to inventory
InventoryItem item1 = new InventoryItem(0, "Laptop", 10, 999.99); // Create first item
InventoryItem item2 = new InventoryItem(0, "Mouse", 50, 19.99); // Create second item
inventoryDAO.addItem(item1); // Add first item to database
inventoryDAO.addItem(item2); // Add second item to database
// Retrieve and print all items
List<InventoryItem> items = inventoryDAO.getAllItems(); // Retrieve all items
for (InventoryItem item : items) {
System.out.println(item); // Print each item
}
// Update an existing item
item1.setName("Gaming Laptop"); // Change name of first item
item1.setPrice(1299.99); // Change price of first item
inventoryDAO.updateItem(item1); // Update item in database
// Delete an item by id
inventoryDAO.deleteItem(item2.getId()); // Delete second item from database
// Retrieve and print all items after update and delete
items = inventoryDAO.getAllItems(); // Retrieve all items again
for (InventoryItem item : items) {
System.out.println(item); // Print each item
}
}
}
Application Diagram
Here’s a simplified diagram of the Inventory Management application:
+--------------------+
| Main |
|--------------------|
| - main(String[] args) |
|--------------------|
| + main(args: String[]) |
+--------------------+
|
v
+--------------------+
| InventoryDAO |
|--------------------|
| - connection: Connection |
|--------------------|
| + InventoryDAO() |
| + addItem(item: InventoryItem) |
| + getAllItems(): List<InventoryItem> |
| + updateItem(item: InventoryItem) |
| + deleteItem(id: int) |
+--------------------+
|
v
+--------------------+
| DatabaseConnection|
|--------------------|
| - URL: String |
| - USER: String |
| - PASSWORD: String|
|--------------------|
| + getConnection(): Connection |
+--------------------+
|
v
+--------------------+
| InventoryItem |
|--------------------|
| - id: int |
| - name: String |
| - quantity: int |
| - price: double |
|--------------------|
| + InventoryItem(id: int, name: String, quantity: int, price: double) |
| + getId(): int |
| + setId(id: int) |
| + getName(): String|
| + setName(name: String)|
| + getQuantity(): int |
| + setQuantity(quantity: int) |
| + getPrice(): double |
| + setPrice(price: double) |
| + toString(): String |
+--------------------+
Welcome to DevTechTutor.com, your ultimate resource for mastering web development and technology! Whether you're a beginner eager to dive into coding or an experienced developer looking to sharpen your skills, DevTechTutor.com is here to guide you every step of the way. Our mission is to make learning web development accessible, engaging, and effective.