Java Notes
Hands-on JDBC projects — Student Management System, Employee Payroll, Library Management with full working code including DAO pattern, connection pooling, and menu-driven interface.
Project 1: Student Management System
A complete console-based CRUD application with the DAO (Data Access Object) pattern.
Database Setup
CREATE DATABASE IF NOT EXISTS student_mgmt;
USE student_mgmt;
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
roll_number VARCHAR(20) UNIQUE NOT NULL,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE,
course VARCHAR(50),
semester INT CHECK (semester BETWEEN 1 AND 8),
gpa DECIMAL(3,2) CHECK (gpa BETWEEN 0.0 AND 4.0),
phone VARCHAR(15),
admission_date DATE,
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
CREATE INDEX idx_course ON students(course);
CREATE INDEX idx_semester ON students(semester);Model Class
import java.time.LocalDate;
public class Student {
private int id;
private String rollNumber;
private String firstName;
private String lastName;
private String email;
private String course;
private int semester;
private double gpa;
private String phone;
private LocalDate admissionDate;
private boolean active;
// Constructors
public Student() {}
public Student(String rollNumber, String firstName, String lastName,
String email, String course, int semester) {
this.rollNumber = rollNumber;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.course = course;
this.semester = semester;
this.admissionDate = LocalDate.now();
this.active = true;
}
// Getters and Setters (omitted for brevity)
@Override
public String toString() {
return String.format("| %-4d | %-10s | %-15s %-15s | %-8s | Sem %d | GPA %.2f |",
id, rollNumber, firstName, lastName, course, semester, gpa);
}
}Database Connection Manager
import java.sql.*;
import java.io.InputStream;
import java.util.Properties;
public class DatabaseManager {
private static final Properties props = new Properties();
static {
try (InputStream is = DatabaseManager.class.getClassLoader()
.getResourceAsStream("db.properties")) {
if (is != null) props.load(is);
else {
props.setProperty("url", "jdbc:mysql://localhost:3306/student_mgmt?useSSL=false&serverTimezone=UTC");
props.setProperty("user", "root");
props.setProperty("password", "password");
}
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (Exception e) {
throw new RuntimeException("Database initialization failed", e);
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(
props.getProperty("url"),
props.getProperty("user"),
props.getProperty("password"));
}
}DAO Interface and Implementation
import java.util.List;
import java.util.Optional;
public interface StudentDAO {
int insert(Student student) throws SQLException;
Optional<Student> findById(int id) throws SQLException;
Optional<Student> findByRollNumber(String rollNumber) throws SQLException;
List<Student> findAll() throws SQLException;
List<Student> findByCourse(String course) throws SQLException;
List<Student> search(String keyword) throws SQLException;
boolean update(Student student) throws SQLException;
boolean delete(int id) throws SQLException;
long count() throws SQLException;
double averageGPA(String course) throws SQLException;
}Main Application (Menu-Driven)
╔══════════════════════════════════════╗ ║ Student Management System v1.0 ║ ╚══════════════════════════════════════╝ \n--- MENU --- 1. Add Student 2. View All Students 3. Search Student 4. Update Student 5. Delete Student 6. View Statistics 0. Exit \n--- Add New Student --- No students found. Total: " + students.size() + " students
Key Takeaways for Projects
- Always use DAO pattern — separates data access from business logic
- Use PreparedStatement — never concatenate user input into SQL
- Close resources — use try-with-resources
- Use transactions — for multi-statement operations
- Connection pooling — mandatory for web applications
- Soft deletes — use
is_activeflag instead of hard DELETE - Proper error handling — catch specific exceptions, provide meaningful messages
Interview Questions
Q1: What is the DAO pattern and why use it?
Answer: DAO (Data Access Object) encapsulates all database operations for an entity in a dedicated class. Benefits: separates persistence logic from business logic, makes code testable (mock the DAO), enables switching databases without changing business code.
Q2: How would you handle pagination in a JDBC application?
Answer: Use LIMIT ? OFFSET ? in MySQL (or FETCH FIRST ? ROWS ONLY in standard SQL). Pass page number and page size as parameters. Calculate offset as (pageNumber - 1) * pageSize. Include a count query for total pages.
Q3: How would you implement connection pooling in a standalone Java app?
Answer: Use HikariCP: create a HikariConfig with URL, credentials, and pool settings (max size, timeouts). Create HikariDataSource and call getConnection(). Connections are returned to pool on close. Shutdown the pool when the app exits.
Q4: How would you secure database credentials in a production app?
Answer: Never hardcode passwords. Use environment variables, encrypted config files, secrets managers (AWS Secrets Manager, HashiCorp Vault), or JNDI DataSource configured by the app server. In CI/CD, inject secrets at deploy time.
Summary
In this chapter, we learned about JDBC Projects in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JDBC Projects.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, jdbc, projects, jdbc projects
Related Java Master Course Topics