Java Reference
In-Depth Information
// No annotation
protected javax.sql.Date creationDate;
9.3.5. Enumerated types
Referring back to
figure 9.4
, suppose the data model contains an enumeration that identifies
the types of users in your application. The enumeration may look similar to the following:
public enum UserType { SELLER, BIDDER, CSR, ADMIN }
Because a relational database doesn't understand Java objects or type hierarchies, you can
use this enumeration to persist data to the table to identify the type of user. A relational
database doesn't understand
enum
types either, so the
UserType
will need to be conver-
ted into something the database can understand. This is where
@Enumerated
comes in.
The
@Enumerated
annotation may be used in either of the following ways:
@Enumerated(EnumType.STRING)
protected UserType userType1;
@Enumerated(EnumType.ORDINAL)
protected UserType userType2;
The difference between the two is that one example uses
EnumType.STRING
and the
other uses
EnumType.ORDINAL
.
EnumType
controls what data type is stored in the
database for the enumeration.
Recall that each enumeration has an associated
String
representation.
User-
Type.SELLER
is represented by
SELLER
,
UserType.BIDDER
by
BIDDER
, and so
on. When
@Enumerated(EnumType.STRING)
is used, JPA will persist this
String
representation to the database.
Recall also that each enumeration has an index representation as well. Given the order
of the enumeration values in the preceding code snippet,
UserType.SELLER
is index
0 and may be retrieved from the enumeration by this index value by
User-
Type.values()[0];
. Similarly,
UserType.BIDDER
is index 1,
UserType.CSR
is index 2, and so on. When
@Enumerated(EnumType.ORDINAL)
is used, JPA will
persist this index (or ordinal) representation to the database.