background image

Creating an Entity Class

<< Defining the Persistence Unit | Obtaining Access to an Entity Manager >>
<< Defining the Persistence Unit | Obtaining Access to an Entity Manager >>

Creating an Entity Class

A resource-local entity manager cannot participate in global transactions. In addition, the web
container will not roll back pending transactions left behind by poorly written applications.
Creating an Entity Class
As explained in
"Accessing Databases from Web Applications" on page 703
, an entity class is a
component that represents a table in the database. In the case of the Duke's Bookstore
application, there is only one database table and therefore only one entity class: the Book class.
The Book class contains properties for accessing each piece of data for a particular book, such as
the book's title and author. To make it an entity class that is accessible to an entity manager, you
need to do the following:
Add the @Entity annotation to the class.
Add the @Id annotation to the property that represents the primary key of the table.
Add the @Table annotation to the class to identify the name of the database table if it is
different from the name of the entity class.
Optionally make the class Serializable.
The following code shows part of the Book class:
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name=
"WEB_BOOKSTORE_BOOKS")
public class Book implements Serializable {
private String bookId;
private String title;
public Book() { }
public Book(String bookId, String title, ...) {
this.bookId = bookId;
this.title = title;
...
}
@Id
public String getBookId() {
return this.bookId;
Accessing Databases from Web Applications
Chapter 25 · Persistence in the Web Tier
705