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 4 ■ MANAGING PERSISTENT OBJECTSListing 4-27. The Customer Entity Defining Named Queries@Entity@NamedQueries({@NamedQuery(name = "findAll", query="select c from Customer c"),@NamedQuery(name = "findVincent", query="select c from Customer c where c.firstName = 'Vincent'"),@NamedQuery(name = "findWithParam", query="select c from Customer c where c.firstName = :fname")})public class Customer {@Id @GeneratedValueprivate Long id;private String firstName;private String lastName;private Integer age;private String email;@OneToOne@JoinColumn(name = "address_fk")private Address address;}// Constructors, getters, settersBecause the Customer entity defines more than one named query, it uses the @NamedQueriesannotation, which takes an array of @NamedQuery. The first query, called findAll, selects all customersfrom the database <strong>with</strong> no restriction (no WHERE clause). The findWithParam query takes the parameter:fname to restrict customers by their first name. Listing 4-27 shows an array of @NamedQueries, but, if theCustomer only had one query, it would have been defined as follows:@Entity@NamedQuery(name = "findAll", query="select c from Customer c")public class Customer {...}The way to execute these named queries resembles the way dynamic queries are used. TheEntityManager.createNamedQuery() method is invoked and passed to the query name defined by theannotations. This method returns a Query or a TypedQuery that can be used to set parameters, the maxresults, fetch modes, and so on. To execute the findAll query, write the following code:Query query = em.createNamedQuery("findAll");List customers = query.getResultList();Again, if you need to type the query to return a list of Customer objects, you’ll need to use theTypedQuery as follows:TypedQuery query = em.createNamedQuery("findAll", Customer.class);List customers = query.getResultList();156s

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

Saved successfully!

Ooh no, something went wrong!