Project
Library Management System (CLI)
Goal: Build a real command-line library system — books, members, loans — with your own classes, idiomatic Collections/streams, JUnit 5 tests and a real SQLite database over JDBC. Time: ~8 hours · Uses: Parts 8–11 (plus everything from Stage 1)
Project brief
A small society or college library still runs on a register: who took which book, when is it due, who owes a fine. In this project you replace that register with a tool you run from the terminal, backed by a real SQLite database.
The library has three rules:
| Rule | Value |
|---|---|
| Books one member can have at the same time | 3 |
| Loan period | 14 days |
| Late fee | ₹5 per day late |
A real run against the sample data (the full script is in tests_manual.md):
$ java -cp .:sqlite-jdbc-3.50.3.0.jar LibraryManager --db demo.db --today 2026-11-26 borrow 1 9
Loan #4: 'Five Point Someone' to Asha Kulkarni, due 2026-12-10.
$ java -cp .:sqlite-jdbc-3.50.3.0.jar LibraryManager --db demo.db --today 2026-11-26 return 1
Returned 'Train to Pakistan' (loan #1): 23 days late, fee ₹115.
$ java -cp .:sqlite-jdbc-3.50.3.0.jar LibraryManager --db demo.db --today 2026-11-26 report
Library report
===============
Books: 9 total, 7 available
Members: 5
Loans: 2 active, 2 overdue
Fees collected so far: ₹115.00
Files
| File | What it is |
|---|---|
README.md |
This brief and the step-by-step build guide |
Book.java, Member.java, Loan.java |
The three model classes — try building these yourself first! |
BookStatus.java |
Enum with a field: AVAILABLE/ON_LOAN, each with its own display label |
LibraryReport.java, OverdueEntry.java |
Plain-data records used for reporting |
LibraryException.java and its subclasses |
The checked exception family every library-rule failure throws |
LibraryStorageException.java |
The one unchecked exception, for a database that is genuinely broken |
LibraryRepository.java |
All the SQL — JDBC, PreparedStatement, row-to-object mapping |
Library.java |
The business rules: borrow, return, overdue, report |
LibraryManager.java |
The command-line entry point (complete reference solution) |
sample_data.sql |
8 books, 4 members and 3 loans to play with |
tests/ |
JUnit 5 tests: ModelsTest, LibraryRepositoryTest, LibraryTest |
tests_manual.md |
Every CLI command to try, with the exact expected output |
How to run
Open a terminal in this folder (JDK 21, see ../../TOOLING.md). This project needs one external jar — the SQLite JDBC driver — the same one Part 11 downloaded into ../part-11-io-apis-and-databases/examples/lib/. Either point at that copy or download your own (see that folder's note in the Part 11 README, section 7):
javac -d out *.java
java -cp out:../part-11-io-apis-and-databases/examples/lib/sqlite-jdbc-3.50.3.0.jar LibraryManager help
java -cp out:../part-11-io-apis-and-databases/examples/lib/sqlite-jdbc-3.50.3.0.jar LibraryManager load-sample
java -cp out:../part-11-io-apis-and-databases/examples/lib/sqlite-jdbc-3.50.3.0.jar LibraryManager list-books
(Windows: use ; instead of : in -cp.)
By default your data is saved in library.db in the current directory. The file (and its tables) is created the first time you run any command. To test safely, work in a scratch folder with --db demo.db, so your real library.db is never touched — see tests_manual.md for the full script.
Global options go before the command:
| Option | What it does |
|---|---|
--db PATH |
Use another SQLite file, e.g. --db demo.db for testing |
--today YYYY-MM-DD |
Pretend today is this date. Makes due dates, overdue reports and fees reproducible |
Running the tests
Download junit-platform-console-standalone-1.14.5.jar the same way Part 10 did (see ../part-10-testing-and-code-quality/examples/lib/README.md for the exact curl + SHA-1 check), then compile and run from this folder:
mkdir -p out
javac -d out -cp junit-platform-console-standalone-1.14.5.jar:../part-11-io-apis-and-databases/examples/lib/sqlite-jdbc-3.50.3.0.jar *.java tests/*.java
java -cp out:junit-platform-console-standalone-1.14.5.jar:../part-11-io-apis-and-databases/examples/lib/sqlite-jdbc-3.50.3.0.jar \
org.junit.platform.console.ConsoleLauncher execute --scan-class-path --details=tree --disable-ansi-colors
Notice this does not run as java -jar junit-platform-console-standalone-1.14.5.jar execute -cp ... the way Part 10 showed — -jar silently ignores any -cp you also pass, and these tests need a second jar (the SQLite driver) on the classpath, not just JUnit's own. Naming the launcher's real main class (org.junit.platform.console.ConsoleLauncher) after an ordinary -cp with both jars sidesteps that; this is the one place this project's test setup differs from Part 10's.
[ 9 containers found ]
[ 9 containers successful ]
[ 38 tests found ]
[ 38 tests successful ]
[ 0 tests failed ]
(The real counts from a verified run — (varies) only if you add or remove tests.)
Features
| Command | What it does | Example |
|---|---|---|
add-book <title> <author> <year> |
Add a book | add-book "A Suitable Boy" "Vikram Seth" 1993 |
add-member <name> <email> |
Add a member (each email only once) | add-member "Kabir Khan" [email protected] |
list-books [available] |
Show all books, or only the ones on the shelf | list-books available |
search <text> |
Find books by title or author (any letter case) | search narayan |
borrow <memberId> <bookId> |
Lend a book. Due 14 days later. Max 3 books per member | borrow 1 6 |
return <loanId> |
Take a book back. ₹5 per day late | return 1 |
overdue |
Loans past their due date, with the fee so far | --today 2026-12-20 overdue |
report |
Totals: books, members, loans, fees collected | report |
load-sample |
Load sample_data.sql into an empty database |
--db demo.db load-sample |
help |
Show the command list | help |
Error handling: a library-rule mistake prints one clear Error: ... line to stderr and exits with code 1. Wrong usage (an unknown option, a missing command, an unparseable --today) exits with code 2.
| Bad input | Message |
|---|---|
borrow 1 6 (member already has 3 books) |
Error: Asha Kulkarni already has 3 books on loan (limit 3). |
borrow 2 9 (book is out) |
Error: 'Five Point Someone' is already on loan. |
borrow 99 1 |
Error: No member with id 99. |
return 99 |
Error: No loan with id 99. |
add-member "Riya Das" riya.example.com |
Error: Email must contain '@', got 'riya.example.com'. |
Architecture
Each layer only talks to the one below it. The CLI never writes SQL; the database layer never knows the rules — the same separation Stage 1's ExpenseTracker kept, now with a real class per responsibility instead of one file:
you type a command
│
▼
┌───────────────────────────┐
│ LibraryManager (CLI) │ reads args[], prints tables, "Error: ..." + exit codes
└────────────┬──────────────┘
│ calls library.borrow(1, 6, today)
▼
┌───────────────────────────┐
│ Library │ the RULES (3 books max, 14 days, ₹5/day)
└────────────┬──────────────┘
│ calls repository.findBook(6), repository.insertLoan(loan) ...
▼
┌───────────────────────────┐
│ LibraryRepository │ all the SQL, PreparedStatement, ? placeholders
└────────────┬──────────────┘
▼
library.db (SQLite file, via JDBC)
Book / Member / Loan / BookStatus and the LibraryException family
are used by every layer.
Why split it like this?
- Easy to test:
LibraryTesttests the rules against an in-memoryjdbc:sqlite::memory:database, with no command line involved. - Easy to change: a future web front end could call the same
Libraryclass; onlyLibraryManagerwould change.
Which Parts each piece uses
| Piece | Skills | Part |
|---|---|---|
Book, Member, Loan as classes with validating constructors |
constructors, encapsulation, this, overloaded constructors |
Part 8, sections 2–3 |
BookStatus |
enum with a field (label()) |
Part 8, section 10 |
Book.equals/hashCode by id, toString |
overriding Object's methods |
Part 8, section 5 |
LibraryReport, OverdueEntry |
plain, immutable data → record |
Part 8, section 11 |
LibraryException family (checked), LibraryStorageException (unchecked, wraps SQLException) |
custom exception design: checked vs. unchecked, wrapping a cause | Part 11, section 1 |
library.findBook(id) returning Optional<Book> |
Optional instead of null-checking |
Part 9, section 9 |
repository.listBooks(...) building a List<Book>, Library.overdue filtering active loans |
the Collections Framework, choosing List/Map |
Part 9, sections 3–5 |
method references in repository.findBook(bookId).map(Book::title) |
method references | Part 9, section 7 |
the Connection handed into LibraryRepository rather than created inside it |
dependency injection for testability — same seam as Part 10's AlertService |
Part 10, section 9 |
tests/ModelsTest.java, LibraryTest.java, LibraryRepositoryTest.java |
@Test, @BeforeEach/@AfterEach, assertThrows, @ParameterizedTest + @CsvSource |
Part 10 |
LibraryRepository |
JDBC, PreparedStatement, ? placeholders, try-with-resources, jdbc:sqlite::memory: for tests |
Part 11, sections 7–8 |
LibraryManager.main, arrow switch dispatch, exit codes |
reading args[] by hand, same convention as the Stage 1 project |
Stage 1 project |
Build it step by step
Build in small steps. Compile and run after every step. Try each one yourself before opening the finished .java files in this folder.
Step 1: Exceptions first (Part 11, section 1)
What and why: decide what can go wrong before writing the rules. One checked base class means LibraryManager needs only one catch for every library-rule problem; one unchecked class covers a database that is genuinely broken.
public class LibraryException extends Exception {
public LibraryException(String message) { super(message); }
}
public class BookNotFoundException extends LibraryException {
public BookNotFoundException(int bookId) {
super("No book with id " + bookId + ".");
}
}
public class LibraryStorageException extends RuntimeException {
public LibraryStorageException(String message, Throwable cause) {
super(message, cause); // never drop the original SQLException
}
}
Add BookNotAvailableException, MemberNotFoundException, LoanNotFoundException, DuplicateEmailException and LoanLimitExceededException the same way — each builds its own message from the data it needs.
✅ Test: new BookNotFoundException(99).getMessage() → "No book with id 99.".
Step 2: Models as classes and an enum (Part 8)
What and why: Book's id is null until the database assigns one; its status genuinely changes while it's "the same" book — that mutability is exactly why Book is a class, not a record. Member and Loan follow the same shape: a constructor for a brand-new row (no id), a full constructor for rebuilding one read back from the database.
public class Book {
private Integer id; // null until the repository saves it
private final String title;
private final String author;
private final int year;
private BookStatus status;
public Book(String title, String author, int year) {
this(null, title, author, year, BookStatus.AVAILABLE);
}
public Book(Integer id, String title, String author, int year, BookStatus status) {
String cleanTitle = title == null ? "" : title.strip();
if (cleanTitle.isEmpty()) {
throw new IllegalArgumentException("Title cannot be empty.");
}
// ... same for author, year > 0, status != null
this.id = id;
this.title = cleanTitle;
this.author = author;
this.year = year;
this.status = status;
}
public boolean isAvailable() { return status == BookStatus.AVAILABLE; }
@Override
public boolean equals(Object o) { // same book = same id, Part 8 section 5
return o instanceof Book other && java.util.Objects.equals(id, other.id);
}
}
BookStatus is an enum with a field — AVAILABLE/ON_LOAN carry a display label the CLI prints, separate from the plain name() that gets stored in the database:
public enum BookStatus {
AVAILABLE("available"), ON_LOAN("on loan");
private final String label;
BookStatus(String label) { this.label = label; }
public String label() { return label; }
}
Member validates its email contains @ and lower-cases it, so [email protected] and [email protected] count as the same address. Loan adds a daysLate(LocalDate asOf) helper and a markReturned(returnedOn, feeRupees) method — the only way returnedOn/feeRupees ever change.
✅ Test: new Book(" ", "Author", 2000) throws IllegalArgumentException; new Loan(2, 1, due.minusDays(14), due).daysLate(due.plusDays(3)) → 3.
🔍 Going deeper:
LibraryReportandOverdueEntryare plain data with no identity — exactly the case Part 8 section 11 makes for arecordinstead of a class:public record OverdueEntry(Loan loan, String bookTitle, String memberName, int daysLate, int feeRupees) {}.
Step 3: LibraryRepository — all the SQL, behind one class (Part 11)
What and why: this is the only class that imports java.sql.*. Every value from outside the source code — a title, a search word — goes through a ? placeholder; nothing here ever concatenates user text into SQL.
public class LibraryRepository {
private final Connection connection; // handed in, not created here
public LibraryRepository(Connection connection) { this.connection = connection; }
public void createSchema() {
String books = """
CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL, author TEXT NOT NULL,
year INTEGER NOT NULL, status TEXT NOT NULL
)""";
// members (UNIQUE email), loans (REFERENCES books/members) the same way
try (Statement statement = connection.createStatement()) {
statement.execute(books);
// ...
} catch (SQLException e) {
throw new LibraryStorageException("could not create the database schema", e);
}
}
public Book insertBook(Book book) {
String sql = "INSERT INTO books (title, author, year, status) VALUES (?, ?, ?, ?)";
try (PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, book.title());
statement.setString(2, book.author());
statement.setInt(3, book.year());
statement.setString(4, book.status().name());
statement.executeUpdate();
try (ResultSet keys = statement.getGeneratedKeys()) {
keys.next();
book.setId(keys.getInt(1));
}
return book;
} catch (SQLException e) {
throw new LibraryStorageException("could not save book '" + book.title() + "'", e);
}
}
}
The connection is handed in, never created inside the class — the same dependency-injection seam Part 10 used for AlertService — so a test can point this class at jdbc:sqlite::memory: instead of a real file. insertMember catches the UNIQUE violation SQLException and rethrows it as DuplicateEmailException; every other repository method either returns an Optional<T>, a List<T>, or throws the unchecked LibraryStorageException.
✅ Test: against jdbc:sqlite::memory:, repository.insertBook(new Book("Malgudi Days", "R. K. Narayan", 1943)).id() → 1, and repository.findBook(1) reads the same row back.
🔍 Going deeper:
runScript(Path sqlFile)is a deliberately small SQL-script runner — split on;, skip--comments, run each statement — good enough for this project's flatINSERTs, not a general parser. It is whatload-samplecalls.
Step 4: Library — the rules, with constants at the top (Part 8, section 4)
What and why: "3 books max", "14 days", "₹5 per day" are the library's rules, not facts about SQL. Keep them in one class as static final constants, so a rule change is a one-line edit.
public class Library {
public static final int MAX_LOANS_PER_MEMBER = 3;
public static final int LOAN_PERIOD_DAYS = 14;
public static final int LATE_FEE_PER_DAY_RUPEES = 5;
private final LibraryRepository repository;
public Loan borrow(int memberId, int bookId, LocalDate today) throws LibraryException {
Member member = repository.findMember(memberId).orElseThrow(() -> new MemberNotFoundException(memberId));
Book book = repository.findBook(bookId).orElseThrow(() -> new BookNotFoundException(bookId));
if (!book.isAvailable()) {
throw new BookNotAvailableException(book.title());
}
if (repository.countActiveLoans(memberId) >= MAX_LOANS_PER_MEMBER) {
throw new LoanLimitExceededException(member.name(), MAX_LOANS_PER_MEMBER);
}
Loan loan = new Loan(bookId, memberId, today, today.plusDays(LOAN_PERIOD_DAYS));
repository.insertLoan(loan);
repository.updateBookStatus(bookId, BookStatus.ON_LOAN);
return loan;
}
}
returnBook(loanId, today) finds the loan, refuses one already returned, computes daysLate(today) * LATE_FEE_PER_DAY_RUPEES, calls loan.markReturned(...), and flips the book back to AVAILABLE. Library never writes SQL itself — it only calls LibraryRepository methods, so tests/LibraryTest.java can test every rule against an in-memory database with no CLI involved.
✅ Test: borrow 3 books for the same member, then a 4th throws LoanLimitExceededException with message "<name> already has 3 books on loan (limit 3).".
🔍 Going deeper: why does
borrow/returnBooktaketodayas a parameter instead of callingLocalDate.now()inside? A test written today would start failing tomorrow. Passing the date in (the same dependency-injection idea as Step 3'sConnection) makes every test — and--todayon the command line — reproducible forever.
Step 5: Overdue report and totals (Part 9, streams/Optional)
What and why: the librarian's daily question is "who is late, and how much?" overdue(today) loops repository.listActiveLoans(), skips loans with daysLate == 0, and builds an OverdueEntry per late loan — looking up the book title and member name with Optional.map(...).orElse(...) instead of a null check:
String title = repository.findBook(loan.bookId()).map(Book::title).orElse("unknown book");
report(today) returns a LibraryReport record with the totals — countBooks(), countAvailableBooks(), countMembers(), countActiveLoans(), overdue(today).size(), sumFeesCollectedRupees().
✅ Test: borrow then return a book 2 days late → report(today).feesCollectedRupees() includes 10.
Step 6: Tests with JUnit 5 (Part 10)
What and why: the rules are money — a test suite proves they still work after every change. Split across three files: ModelsTest (constructors, equals, daysLate — no database at all), LibraryRepositoryTest (the SQL, against jdbc:sqlite::memory:), LibraryTest (the rules, through Library, also in-memory).
class LibraryTest {
private Connection connection;
private Library library;
private int bookId, memberId;
@BeforeEach
void freshLibraryWithOneBookAndOneMember() throws SQLException, LibraryException {
connection = DriverManager.getConnection("jdbc:sqlite::memory:");
LibraryRepository repository = new LibraryRepository(connection);
repository.createSchema();
library = new Library(repository);
bookId = library.addBook("Malgudi Days", "R. K. Narayan", 1943).id();
memberId = library.addMember("Asha Kulkarni", "[email protected]").id();
}
@AfterEach
void closeConnection() throws SQLException { connection.close(); }
@ParameterizedTest(name = "{0} days late costs Rs {1}")
@CsvSource({"0, 0", "1, 5", "11, 55", "30, 150"})
void returnBook_chargesLateFeePerDay(int daysLate, int expectedFee) throws LibraryException {
Loan loan = library.borrow(memberId, bookId, LocalDate.of(2026, 11, 15));
Loan returned = library.returnBook(loan.id(), loan.dueOn().plusDays(daysLate));
assertEquals(expectedFee, returned.feeRupees());
}
}
A fresh in-memory database for every test (@BeforeEach/@AfterEach) means one test's rows never leak into the next — the same reason Part 10's BankAccountTest rebuilt its account every time.
✅ Test: all 38 tests green — see "Running the tests" above for the exact command.
Step 7: LibraryManager — the CLI (Stage 1 project pattern)
What and why: this is the only class that reads args[], opens the JDBC connection, and prints anything. Global options (--db, --today) are parsed first, then the command name dispatches with an arrow switch:
try (Connection connection = DriverManager.getConnection("jdbc:sqlite:" + dbPath)) {
LibraryRepository repository = new LibraryRepository(connection);
repository.createSchema();
Library library = new Library(repository);
switch (rest[0]) {
case "borrow" -> handleBorrow(rest, library, today);
case "return" -> handleReturn(rest, library, today);
// ...
default -> throw new LibraryException("Unknown command '" + rest[0] + "'. ...");
}
} catch (LibraryException | IllegalArgumentException | LibraryStorageException e) {
System.err.println("Error: " + e.getMessage());
System.exit(1);
} catch (SQLException e) {
System.err.println("Error: database problem with " + dbPath + " (" + e.getMessage() + ").");
System.exit(1);
}
Exit codes follow the Stage 1 convention: 0 success, 1 an error the user can fix, 2 wrong command-line usage (unknown option, missing command, an unparseable --today).
✅ Test: run every command and error case in tests_manual.md. Output and exit code must match exactly.
🔍 Going deeper:
PRAGMA foreign_keys = ONis set right after opening the connection — SQLite does not enforceREFERENCESconstraints unless this pragma is turned on for every connection, unlike most other databases where foreign keys are on by default.
Step 8: Sample data (Part 11)
What and why: a demo needs data. sample_data.sql is plain INSERT statements with fixed ids, so tests_manual.md can say "book 9" and mean the same book every time. load-sample refuses to run on a database that already has books or members, so it only ever runs once per file.
✅ Test: --db demo.db load-sample → Loaded sample data: 8 books, 4 members, 3 active loans.
Stretch goals
- 🟢
list-memberscommand: id, name, email and how many books each one currently has out. - 🟢
history <memberId>: every loan a member has ever taken, with dates and fees. - 🟡 More than one copy of a book: a
copiescolumn, counting active loans against it instead of a singlestatus. - 🟡
renew <loanId>: add 14 more days, but only once and only if the loan is not already overdue. - 🟡 Rewrite
Library.overdue/reportusing Stream pipelines (repository.listActiveLoans().stream().filter(...).map(...)) instead of a plain loop — compare readability both ways. - 🔴 Replace the hand-rolled
runScriptwith a transaction (connection.setAutoCommit(false), commit once at the end) so a half-broken sample file never leaves a half-loaded database. - 🔴 A generic
Repository<T>wrapper (Part 9, section 2) around the three id-lookup patterns (findBook,findMember,findLoan) thatLibraryRepositorycurrently repeats three times.
Checklist
- I can design a small class with a validating constructor, and override
equals/hashCode/toString. - I can write an enum with a field and a method.
- I can design a checked exception family with one base class, and one unchecked exception that wraps a cause.
- I can write JDBC with
PreparedStatement,?placeholders, andtry-with-resources — never string-concatenated SQL. - I can keep business rules in one class with named constants, and pass
todayin rather than reading the clock. - I can write JUnit 5 tests with
@BeforeEach/@AfterEach,assertThrows, and@ParameterizedTest+@CsvSource, against an in-memory SQLite database. - I understand why
java -jar X.jar ... -cp Ysilently ignores-cp, and when to call the launcher's main class directly instead. - All 38 tests pass and every command in
tests_manual.mdgives the expected output and exit code.
Next
🎉 Stage 2 done! Go back to the roadmap and get ready for Stage 3: Advanced (concurrency, JVM internals, modern Java, build tools).