Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 39 ยท Projects and Practice

Project: A Library Repository Layer

Build a small library system - entities, a repository layer, a fetch-aware query and a statement-count check - with Hibernate code and a runnable JDBC stand-in.

This project ties the course together. You will design a small library domain (authors, books, loans), write the Hibernate mappings and repository methods, and verify the important behaviours: no N+1 queries, a unique ISBN and correct loan rules. The Hibernate code is read-only here; the runnable parts rebuild the same repository on JDBC and H2 so you can run and change every step.

Hibernate is not available in the browser. The mapping code below is what you would put in a real project. The runnable programs are labelled stand-ins that follow the same repository interface.

Step 1: the domain

Three concepts: an Author writes many Books, and a Loan records that a Member borrowed a Book between two dates. A book can only have one open loan at a time.

erDiagram
    AUTHOR ||--o{ BOOK : writes
    BOOK ||--o{ LOAN : "is lent in"
    MEMBER ||--o{ LOAN : borrows
    AUTHOR { long id string name }
    BOOK { long id string isbn string title long author_id int version }
    LOAN { long id long book_id long member_id date borrowed_on date returned_on }
    MEMBER { long id string email }

The foreign keys live on the "many" side: books point to authors, loans point to books and members.

Step 2: the mappings

Java
@Entity
public class Author {
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) Long id;
    @Column(nullable = false) String name;
    @OneToMany(mappedBy = "author") Set<Book> books = new HashSet<>();
}

@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = "isbn"))
public class Book {
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) Long id;
    @NaturalId @Column(nullable = false, length = 17) String isbn;
    @Column(nullable = false) String title;
    @ManyToOne(fetch = FetchType.LAZY, optional = false) Author author;
    @Version int version;

    @Override public boolean equals(Object o) { return o instanceof Book b && Objects.equals(isbn, b.isbn); }
    @Override public int hashCode() { return Objects.hashCode(isbn); }
}

@Entity
public class Loan {
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) Long id;
    @ManyToOne(fetch = FetchType.LAZY, optional = false) Book book;
    @ManyToOne(fetch = FetchType.LAZY, optional = false) Member member;
    @Column(nullable = false) LocalDate borrowedOn;
    LocalDate returnedOn;                       // null while the loan is open
}

Choices to notice: lazy @ManyToOne everywhere, sequence ids (batching works), the ISBN as a natural id with equals/hashCode based on it, and a @Version on the book. These follow Hibernate Best Practices and Anti-Patterns.

Step 3: the repository

Java
public class BookRepository {
    private final SessionFactory sessionFactory;

    public Optional<Book> findByIsbn(String isbn) {
        return sessionFactory.fromSession(s ->
            s.byNaturalId(Book.class).using("isbn", isbn).loadOptional());
    }

    /** Titles with author names in ONE statement, as a DTO projection. */
    public List<BookView> catalog() {
        return sessionFactory.fromSession(s -> s.createQuery("""
            select new com.acme.library.BookView(b.isbn, b.title, a.name)
            from Book b join b.author a
            order by b.title
            """, BookView.class).getResultList());
    }

    /** Open loans with book and member fetched, no N+1. */
    public List<Loan> openLoans() {
        return sessionFactory.fromSession(s -> s.createQuery("""
            from Loan l join fetch l.book join fetch l.member
            where l.returnedOn is null
            """, Loan.class).getResultList());
    }
}

The service enforces the rule "one open loan per book":

Java
public void lend(String isbn, long memberId, LocalDate today) {
    sessionFactory.inTransaction(s -> {
        Book book = s.byNaturalId(Book.class).using("isbn", isbn).load();
        boolean open = s.createQuery("select count(l) from Loan l where l.book = :b and l.returnedOn is null", Long.class)
            .setParameter("b", book).getSingleResult() > 0;
        if (open) throw new IllegalStateException("already lent");
        s.persist(new Loan(book, s.getReference(Member.class, memberId), today));
        s.lock(book, LockModeType.OPTIMISTIC_FORCE_INCREMENT);   // two concurrent lends conflict
    });
}

The forced version increment on the book makes two simultaneous lends of the same book collide at commit, so the check-then-insert race cannot create two open loans (see Optimistic Locking with @Version).

Step 4: run the same design (JDBC stand-in)

Java Library repository on JDBC (stand-in for the Hibernate version)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Step 5: your extensions

Try these on your own, in either the stand-in or a real Hibernate project:

  1. Add returnBook(isbn, date) that sets returned_on and fails if no loan is open.
  2. Add an overdue report: loans older than 14 days still open, with the member email, in one statement.
  3. Add a search(String text) that pages results with keyset paging.
  4. Write a test that asserts catalog() runs exactly one statement (see Testing Hibernate Code).
  5. Add a unique constraint so one member cannot hold more than three open loans, or enforce it in the service with a locking read on the member row.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Why is the Book id generated with a sequence instead of IDENTITY in this design?

    With a sequence Hibernate knows the id without running the insert first, which keeps batching possible.
  2. 2. What does the OPTIMISTIC_FORCE_INCREMENT lock on the book achieve in lend()?

    Both transactions try to increment the same version, so only one commit succeeds.
  3. 3. Why does catalog() use a DTO projection?

    A read-only screen needs three values; a projection fetches them in a single query without managed entities.

Summary

  • Model aggregates with lazy associations, natural ids, sequences and a version column.
  • Keep repositories small: projections for screens, join fetch for loans, natural-id lookups for books.
  • Enforce rules that span rows with a lock or a forced version increment.
  • Verify behaviour with a real database and a statement budget.

Next: Project: Money Transfers with Locking and Retries