12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 2 ■ JAVA PERSISTENCENote that for better readability I’ve omitted the constructor, getters, and setters of this class. As youcan see in this code, except for a few annotations, Book is a simple POJO. Now let’s write a Main class thatpersists a book to the database.Writing the Main ClassThe Main class, shown in Listing 2-4, is under the same directory as the Book entity. It commences bycreating a new instance of the Book entity (using the <strong>Java</strong> keyword new) and sets some values to itsattributes. There is nothing special here, just pure <strong>Java</strong> code. It then uses the Persistence class to get aninstance of an EntityManagerFactory that refers to a persistence unit called chapter02PU, which I’lldescribe later in the section “Persistence Unit for the Main Class.” This factory creates an instance of anEntityManager (em variable). As mentioned previously, the entity manager is the central piece of the JPAin that it is able to create a transaction, persist the Book object using the EntityManager.persist()method, and then commit the transaction. At the end of the main() method, both the EntityManager andEntityManagerFactory are closed to release the provider’s resources.Listing 2-4. A Main Class Persisting a Book Entitypackage com.apress.javaee6.chapter02;public class Main {public static void main(String[] args) {// Creates an instance of bookBook book = new Book();book.setTitle("The Hitchhiker's Guide to the Galaxy");book.setPrice(12.5F);book.setDescription("Science fiction comedy book");book.setIsbn("1-84023-742-2");book.setNbOfPage(354);book.setIllustrations(false);// Gets an entity manager and a transactionEntityManagerFactory emf = Persistence.createEntityManagerFactory("chapter02PU");EntityManager em = emf.createEntityManager();// Persists the book to the databaseEntityTransaction tx = em.getTransaction();tx.begin();em.persist(book);tx.commit();}}em.close();emf.close();52

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!