Java Reference
In-Depth Information
optional. The first attribute is named optional and takes a boolean . Defaulting to true , this
can be set to false to provide a hint to schema generation that the associated column should
be created NOT NULL . The second is named fetch and takes a member of the enumeration
FetchType . This is EAGER by default, but can be set to LAZY to permit loading on access of the
value.
The use of lazy loading is unlikely to be valuable, except when large serializable objects
have been mapped as basic types (rather than given entity mappings of their own) and
retrieval time may become significant. While the (default) EAGER value must be honored, the
LAZY flag is considered to be a hint, and can be ignored by the persistence engine.
The @Basic attribute is usually omitted, with the @Column attribute being used where
the @Basic annotation's optional attribute might otherwise be used to provide the NOT NULL
behavior.
Omitting Persistence with @Transient
Some fields may be used at run time only, and should be discarded from objects as they are
persisted into the database. The EJB 3 specification provides the @Transient annotation for
these transient fields. The @Transient annotation does not have any attributes—you just add
it to the instance variable or the getter method as appropriate for the entity bean's property
access strategy.
For our example, we contrive to add a Date field named publicationDate , which will not
be stored in the database to our Book class. We mark this field transient thus:
@Transient
public Date getPublicationDate() {
return publicationDate;
}
Because we are using a property access strategy for our Book class, we must put the
@Transient annotation on the getter method.
Mapping Properties and Fields with @Column
The @Column annotation is used to specify the details of the column to which a field or prop-
erty will be mapped. Some of the details are schema related, and therefore apply only if the
schema is generated from the annotated files. Others apply and are enforced at run time by
Hibernate (or the EJB 3 persistence engine). It is optional, with an appropriate set of default
behaviors, but is often useful when overriding default behavior, or when you need to fit your
object model into a preexisting schema. It is more commonly used than the similar @Basic
annotation, with the following attributes commonly being overridden:
name permits the name of the column to be explicitly specified—by default, this would
be the name of the property. However, it is often necessary to override the default
behavior when it would otherwise result in an SQL keyword being used as the column
name (e.g., user ).
length permits the size of the column used to map a value (particularly a String value)
to be explicitly defined. The column size defaults to 255, which might otherwise result
in truncated String data, for example.
Search WWH ::




Custom Search