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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 2 ■ JAVA PERSISTENCEknown as named queries, are defined using either annotations or XML metadata. The previous JPQLstatement can, for example, be defined as a named query on the Book entity.Listing 2-2 shows a Book entity defining the findBookByTitle named query using the @NamedQueryannotation.Listing 2-2. A findBookByTitle Named Query@Entity@NamedQuery(name = "findBookByTitle", query = "SELECT b FROM Book b WHERE b.title ='H2G2'")public class Book {@Id @GeneratedValueprivate Long id;@Column(nullable = false)private String title;private Float price;@Column(length = 2000)private String description;private String isbn;private Integer nbOfPage;private Boolean illustrations;}// Constructors, getters, settersAs you will see in Chapter 4, the EntityManager.createNamedQuery() method is used to execute thequery and return a list of Book entities that match the search criteria.Callbacks and ListenersEntities are just Plain Old <strong>Java</strong> Objects (POJOs). When they are managed by the entity manager, theyhave a persistence identity, and their state is synchronized <strong>with</strong> the database. When they are notmanaged (i.e., they are detached from the entity manager), they can be used like any other <strong>Java</strong> class.This means that entities have a life cycle, as shown in Figure 2-3. When you create an instance of theBook entity <strong>with</strong> the new operator, the object exists in memory, and JPA knows nothing about it (it caneven end up being garbage collected). When it becomes managed by the entity manager, its state ismapped and synchronized <strong>with</strong> the BOOK table. Calling the EntityManager.remove() method deletes thedata from the database, but the <strong>Java</strong> object continues living in memory until it gets garbage collected.49

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

Saved successfully!

Ooh no, something went wrong!