10.12.2012 Views

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

A resource-local entity manager cannot participate in global transactions. In addition, the web<br />

container will not roll back pending transactions left behind by poorly written applications.<br />

Creating an Entity Class<br />

As explained in “Accessing Databases from Web Applications” on page 701, an entity class is a<br />

component that represents a table in the database. In the case of the Duke’s Bookstore<br />

application, there is only one database table and therefore only one entity class: the Book class.<br />

<strong>The</strong> Book class contains properties for accessing each piece of data for a particular book, such as<br />

the book’s title and author. To make it an entity class that is accessible to an entity manager, you<br />

need to do the following:<br />

■ Add the @Entity annotation to the class.<br />

■ Add the @Id annotation to the property that represents the primary key of the table.<br />

■ Add the @Table annotation to the class to identify the name of the database table if it is<br />

different from the name of the entity class.<br />

■ Optionally make the class Serializable.<br />

<strong>The</strong> following code shows part of the Book class:<br />

import java.io.Serializable;<br />

import javax.persistence.Entity;<br />

import javax.persistence.Id;<br />

import javax.persistence.Table;<br />

@Entity<br />

@Table(name="WEB_BOOKSTORE_BOOKS")<br />

public class Book implements Serializable {<br />

private String bookId;<br />

private String title;<br />

public Book() { }<br />

public Book(String bookId, String title, ...) {<br />

this.bookId = bookId;<br />

this.title = title;<br />

...<br />

}<br />

@Id<br />

public String getBookId() {<br />

return this.bookId;<br />

Accessing Databases fromWeb Applications<br />

Chapter 25 • Persistence in theWebTier 703

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

Saved successfully!

Ooh no, something went wrong!