Java Reference
In-Depth Information
name
is the name of the discriminator column.
discriminatorType
is the type of value to be stored in the column as selected from the
javax.persistence.DiscriminatorType
enumeration of
STRING
,
CHAR
, or
INTEGER
.
columnDefinition
is a fragment of DDL defining the column type. Using this is liable
to reduce the portability of your code across databases.
length
is the column length of
STRING
discriminator types. It is ignored for
CHAR
and
INTEGER
types.
All of these (and the annotation itself ) are optional, but we recommend supplying at least
the
name
attribute. If no
@DiscriminatorColumn
is specified in the hierarchy, a default column
name of
DTYPE
and type of
STRING
will be used.
Hibernate will supply an appropriate discriminator value for each of your entities. For
example, if the
STRING
discriminator type is used, the value this column contains will be the
name of the entity (which defaults to the class name). You can also override this behavior with
specific values using the
@DiscriminatorValue
annotation. If the discriminator type is
INTEGER
,
any value provided via the
@DiscriminatorValue
annotation must be convertible directly into
an integer.
In Listing 6-22, we specify that an
INTEGER
discriminator type should be stored in the
column named
DISCRIMINATOR
. Rows representing
Book
entities will have a value of
1
in
this column, whereas the following mapping in Listing 6-23 requires that rows represent-
ing
ComputerBook
entities should have a value of
2
in the same column.
Listing 6-22.
The Root of the Inheritance Hierarchy Mapped with the
SINGLE_TABLE
Strategy
@Entity
@Inheritance(strategy = SINGLE_TABLE)
@DiscriminatorColumn(
name="DISCRIMINATOR",
discriminatorType=INTEGER
)
@DiscriminatorValue("1")
public class Book {
...
}
Listing 6-23.
A Derived Entity in the Inheritance Hierarchy
@Entity
@DiscriminatorValue("2")
public class ComputerBook extends Book {
...
}
An alternative to the monolithic single table approach is the otherwise similar joined
table approach. Here a discriminator column is used, but the fields of the various derived
types are stored in distinct tables. Other than the differing strategy, this inheritance type is
specified in the same way (as shown in Listing 6-24).
Search WWH ::
Custom Search