7. Step 7 - Implement the Delete Use Case

The destroy action method of the BookController invokes the Book.destroy method by providing the ISBN of the Book object to be deleted:

public class BookController {
  public String destroy( String isbn) {
    try {
      Book.destroy( em, ut, isbn);
    } catch ( Exception e) {
    return "delete";

The Book.destroy method first retrieves the Book object to be deleted, and then invokes the entity manager's remove method on it:

public class Book {
  public static void destroy( EntityManager em, UserTransaction ut, String isbn) 
      throws Exception, HeuristicRollbackException, RollbackException {
    Book book = em.find( Book.class, isbn);
    em.remove( book);

The view for the Delete action provides a selection list for selecting the book to be deleted. A "Delete" button allows performing the deletion of the selected book. The code of the view in WebContent/views/books/delete.xhtml is as follows:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="..." xmlns:h="..." xmlns:f="...">
  <ui:composition template="/WEB-INF/templates/page.xhtml">
    <ui:define name="main">
      <h:form id="deleteBookForm">
        <h:panelGrid columns="2">
          <h:outputText value="Select book: " />
          <h:selectOneMenu value="#{book.isbn}">
            <f:selectItems value="#{bookCtrl.books}" var="b" 
                itemValue="#{b.isbn}" itemLabel="#{b.title}" />
        <h:commandButton value="Delete" 
            action="#{bookCtrl.destroy( book.isbn)}"/>
      <h:button value="Main menu" outcome="index" />

As in the Update use case, a h:selectOneMenu element is used to create and populate a selection list containing all the books to choose from. Clicking on the "Delete" command button results in invoking the destroy action method of the controller with the isbn value of the selected book, thus resulting in the deletion of the Book object from the database.