Container-managed persistence (CMP) fields are virtual fields whose
values map directly to the database.
Persistence
fields can be Java serializable types and Java primitive types. Java
serializable types implement the
java.io.Serializable
interface. Most deployment tools easily
handle java.lang.String
,
java.util.Date
, and the primitive wrappers
(Byte
, Boolean
,
Short
, Integer
,
Long
, Double
, and
Float
), because these types of objects are part of
the Java core and map naturally to database fields.
The CustomerEJB
declares three serializable
fields, id
, lastName
, and
firstName
, which map naturally to the
INT
and CHAR
fields of the
CUSTOMER
table in the database.
You can also define your own serializable types, called dependent value classes , and declare them as CMP fields. However, I recommend that you do not use custom serializable objects as persistence field types unless it is absolutely necessary—they are usually recommended for unstructured types, such as multimedia data (images, blobs, etc.). Arbitrary dependent value classes usually will not map naturally to database types, so they must be stored in their serializable forms in some type of binary database field.
Serializable objects are always returned as copies and not
references, so modifying a serializable object will not impact its
database value. The value of a serializable object must be updated
using the set<field-name>
method.
The primitive types (byte
,
short
, int
,
long
, double
,
float
, and boolean
) are also
allowed to be CMP
fields. These types are easily mapped to the database and are
supported by all deployment tools. As an example, the
CustomerEJB
might declare a
boolean
that represents a
customer’s credit worthiness:
public abstract class CustomerBean implements javax.ejb.EntityBean { public Integer ejbCreate(Integer id){ setId(id); return null; } // abstract accessor methods public abstract boolean getHasGoodCredit( ); public abstract void setHasGoodCredit(boolean creditRating); ... }
You must add a database field, HAS_GOOD_CREDIT
, to
the CUSTOMER
table for the
hasGoodCredit
persistent field. Depending on the
kind of database you are using, this field may be a
BIT
, INT
,
BOOLEAN
, or something else. For example, Oracle
and DB2 use an INT
field:
CREATE TABLE CUSTOMER
{
ID INT PRIMARY KEY,
LAST_NAME CHAR(20),
FIRST_NAME CHAR(20),
HAS_GOOD_CREDIT INT
}
Other databases use different data types for the
HAS_GOOD_CREDIT
field:
In Oracle, it should be INT
.
In DB2 UDB, it should be INT
.
In SQL*Server, it should be BIT
.
In Sybase ASE, it should be BIT
.
In Cloudscape, it should be BOOLEAN
.
In PointBase, it should be BOOLEAN
.
This is an unfortunate SQL portability problem that occurs when
you’re using different database technologies, but
it’s the only inconsistency I discovered while
testing the code for this book. Before adding the
HAS_GOOD_CREDIT
field to the
CUSTOMER
table, check your
vendor’s documentation to determine the field type.
13.58.50.156