book.setBookCoverImage(new BookCoverImage());
book.getBookCoverImage().setType("image/jpg");
List<BookReview> bookReviews = book.getBookReviews();
BookReview bookReview = new BookReview();
bookReview.setRating(5);
bookReviews.add(bookReview);
bookReview = new BookReview();
bookReview.setRating(4);
bookReviews.add(bookReview);
EntityTransaction txn = em.getTransaction();
txn.begin();
try {
// When the Book is made persistent, the "PERSIST"
// action cascades to the BookCoverImage object and
// all BookReview objects.
em.persist(book);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
} finally {
em.close();
}
try {
em = emf.createEntityManager();
Book book = em.find(Book.class, "978-0141185064");
if (book != null) {
out.println("<p>Found <i>" + book.getTitle() + "</i></p>");
// Automatically fetch the BookCoverImage entity and access a field.
out.println("<p>Book cover image type: " + book.getBookCoverImage().getType() + "</p>");
out.println("<p>Ratings: ");
for (BookReview bookReview : book.getBookReviews()) {
out.println("[" + bookReview.getRating() + "] ");
}
out.println("</p>");
} else {
out.println("Could not find that book I was looking for...");