@Documented
@Retention(RUNTIME)
@Target(FIELD)
public @interface KeyField
Comparable
interface is not implemented. The KeyField
integer value specifies the sort order of this field within the set of
fields in the composite key.
If the field type of a PrimaryKey
or SecondaryKey
is a
composite key class containing more than one key field, then a
KeyField
annotation must be present on each non-transient instance field of
the composite key class. The KeyField
value must be a number
between one and the number of non-transient instance fields declared in the
composite key class.
Note that a composite key class is a flat container for one or more
simple type fields. All non-transient instance fields in the composite key
class are key fields, and its superclass must be Object
.
For example:
@Entity class Animal { @PrimaryKey Classification classification; ... } @Persistent class Classification { @KeyField(1) String kingdom; @KeyField(2) String phylum; @KeyField(3) String clazz; @KeyField(4) String order; @KeyField(5) String family; @KeyField(6) String genus; @KeyField(7) String species; @KeyField(8) String subspecies; ... }
This causes entities to be sorted first by kingdom
, then by
phylum
within kingdom
, and so on.
The fields in a composite key class may not be null.
To override the default sort order, a composite key class may implement
the Comparable
interface. This allows overriding the sort order and
is therefore useful even when there is only one key field in the composite
key class. For example, the following class sorts Strings using a Canadian
collator:
import java.text.Collator; import java.util.Locale; @Entity class Animal { ... @SecondaryKey(relate=ONE_TO_ONE) CollatedString canadianName; ... } @Persistent class CollatedString implements Comparable<CollatedString> { static Collator collator = Collator.getInstance(Locale.CANADA); @KeyField(1) String value; CollatedString(String value) { this.value = value; } private CollatedString() {} public int compareTo(CollatedString o) { return collator.compare(value, o.value); } }
Several important rules should be considered when implementing a custom comparison method. Failure to follow these rules may result in the primary or secondary index becoming unusable; in other words, the store will not be able to function.
Environment
constructor.Modifier and Type | Required Element | Description |
---|---|---|
int |
value |
Copyright (c) 1996, 2020 Oracle and/or its affiliates. All rights reserved.