For the Delete use case, the
delete action method of the BookController
invokes the Book.delete method by providing the ISBN of the
Book object to be deleted:
public class BookController { ... public String delete( String isbn) { try { Book.delete( em, ut, isbn); } catch ( Exception e) { e.printStackTrace(); } return "delete"; } ... }
The Book.delete 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 delete( EntityManager em, UserTransaction ut, String isbn) throws Exception, HeuristicRollbackException, RollbackException { ut.begin(); Book book = em.find( Book.class, isbn); em.remove( book); ut.commit(); } ... }
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="headerTitle">
<h1>Delete a book record</h1>
</ui:define>
<ui:define name="main">
<h:form id="deleteBookForm">
<div><h:outputLabel for="selectBook" value="Select book: ">
<h:selectOneMenu id="selectBook" value="#{book.isbn}">
<f:selectItems value="#{bookCtrl.books}" var="b"
itemValue="#{b.isbn}" itemLabel="#{b.title}"/>
</h:selectOneMenu>
</h:outputLabel></div>
<div><h:commandButton value="Delete"
action="#{bookCtrl.delete( book.isbn)}"/>
</div>
</h:form>
</ui:define>
</ui:composition>
</html>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 delete 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.