Implementing Entity Classes: The Basics
From Wiki
An entity is a persistence domain object. Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. The persistent state of an entity is represented either through its persistent properties. These properties use object/relational mapping annotations to map the entities and entity relationships to the relational data in the underlying data store.
Contents |
Basic Requirements
EJB3 annotations are in the javax.persistence.* package. Most JDK 5 compliant IDE (like Eclipse, IntelliJ IDEA and Netbeans) can autocomplete annotation interfaces and attributes for you (even without a specific "EJB3" module, since EJB3 annotations are plain JDK 5 annotations).
Entity Classes
- The class must be annotated with the
javax.persistence.Entity(@Entity) annotation. Optional you may specify the corresponding table name (@Table). - The class must have a
publicorprotected, no-argument constructor. The class may have other constructors. - The entity class must be a top-level class. An
enumorinterfaceshould not be designated as an entity. - The class must not be declared
final. No operations or persistent properties must be declaredfinal. - The class must follow the method conventions of Java Beans components.
- If an entity instance be passed by value as a detached object, such as through a session bean's remote business interface, the class must implement the
java.io.Serializableinterface. - Entities may extend both entity and non-entity classes.
- Persistent properties must be declared
private,protected, or package-private, and can be accessed directly only by the entity class's methods. Clients should access the entity's state only through accessors (setXXX, getXXX) or business methods.
Persistent Properties
- Must be of the following Java language types: Java primitive types,
java.lang.String, - other serializable types including: wrappers of Java primitive types (such as
Integer),java.math.BigInteger,java.math.BigDecimal,java.util.Date,java.util.Calendar,java.sql.Date,java.sql.Time,java.sql.TimeStamp,byte[],Byte[],char[],Character[] - enumerated types (enums)
- other entities and/or collections of entities
- Collection-valued properties must implement the
java.util.Collectioninterfaces. The following collection interfaces may be used:java.util.Collection,java.util.Set,java.util.List,java.util.Map. Generic variants of these collection types may also be used. - Mapping annotations cannot be applied to fields or properties annotated with
@Transient.
Primary Keys
- Every entity must have a primary key. The key enables clients to locate a particular entity instance. An entity may have either a simple or a composite primary key.
- Simple primary keys use the
javax.persistence.Id(@Id) annotation to denote the primary key property or field. Keys can be auto-generated (see@GeneratedValue - The primary key, or the properties of a composite primary key, must be one of the following Java language types: Java primitive types, Java primitive wrapper types,
java.lang.String,java.util.Date,java.sql.Date - Floating point types should never be used in primary keys.
An Example
TODO: describe Books
TODO: Describe Text books
TODO: Describe Publishers
TODO: Describe Persons
TODO: Describe roles and relationships
Basic Relational Mapping
A developer can take two directions when implementing entity beans. Here we start from a Java object model and derive a database schema from this model. Other applications have an existing database schema from which they have to derive a Java object model.
- Most persistence vendors have tools that can autogenerate database schemas based on the annotations or XML metadata you provide in your code.
- Prototyping your application is fast and easy, as you do not have to define much metadata in order for the persistence engine to generate a schema for you.
- When you want to fine-tune your mappings, the Java Persistence specification has the necessary annotations and XML mappings to do this.
- You will probably not have a need for annotations such as
@Tableand@Column, as you will rely on well-defined specification defaults.
If you have an existing database schema, many vendors have tools that can generate Java entity code directly from it. However,this generated code is not very object-oriented and doesn't map to your database very well. In addition, you will find that a lot more metadata will need to be specified.
Define entity classes: Essential tasks
Declaring an entity bean
Every persistent bean class (POJO) is an entity bean and is declared using the @Entity annotation (at the class level):
package entities;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="books")
public class Book implements Serializable{
private String isbn;
//...
@Id
public String getIsbn() {
return isbn;
}
//...
}
- The
@Idannotation declares a simple primary key of this entity bean. - The
@Tableis optional. This annotation may also contain a schema and a catalog attributes, if they need to be defined. You can also define unique constraints to the table using the@UniqueConstraintannotation in conjunction with@Table(for a unique constraint bound to a single column, refer to@Column).
@Entity
@Table(
name="books",
uniqueConstraints=
@UniqueConstraint(columnNames={"isbn", "year"})
)
public class Book implements Serializable {
//...
}
@Column(name="desc", nullable=false, length=512)
public String getDescription() {
return description;
}
Note on JBoss AS: Depending on whether you annotate fields or methods, the access type used by Hibernate will be field or property. The EJB3 specification requires that you declare annotations on the element type that will be accessed, i.e. the getter method if you use property access, the field if you use field access. Mixing EJB3 annotations in both fields and methods should be avoided. Hibernate will guess the access type from the position of@Idor@EmbeddedId.
Manage the life-cycle of an entity instance
Define entity beans: Add life-cycle event handlers
Package and deploy entity classes
References
- JSR 220
-
javax.persistence.* - Bill Burke and Richard Monson-Haefel, Enterprise JavaBeans, 3.0, O'Reilly, May 16, 2006, ISBN-10: 0-596-00978-X
- EJB3 tutorial on JBoss, retrieved October 15, 2008

