Java Reference
In-Depth Information
COLLECTION ORDERING
EJB 3 does not provide for maintaining the ordering of an ordered collection such as an array or a list—
see the “Ordering Collections with @IndexColumn ” section of the chapter for discussion on how the
@IndexColumn annotation can be used in a non-portable way to remedy this deficiency. The collection,
however, can be specified in terms of the fields of the associated entity at retrieval time by means of the
@OrderBy annotation. For example, if we were to retrieve a list ordered by the topics' names in ascend-
ing order, we could annotate a suitable method.
The following code snippet specifies a retrieval order for an ordered collection.
@OneToMany(cascade = ALL, mappedBy = "publisher"
@OrderBy("name ASC")
public List<Book> getBooks() {
return books
}
The value of the @OrderBy annotation is an ordered list of the field names to sort by, each one option-
ally appended with ASC (for ascending order, as in the preceding code) or DESC (for descending order). If
neither ASC nor DESC is appended to one of the field names, the order will default to ascending. @OrderBy
can be applied to any collection-valued association.
The mappedBy attribute is mandatory on a bidirectional association and optional (being
implicit) on a unidirectional association.
cascade is optional, taking a member of the javax.persistence.CascadeType enumeration
and dictating the cascade behavior of the mapped entity.
targetEntity is optional, as it can usually be deduced from the type of the field or prop-
erty, as in Listing 6-15, where the property represents a Set of Book entities, making the target
entity implicitly Book . However, if necessary (if generics are not being used, for example), the
class of the target entity can be provided here.
fetch is optional, allowing lazy or eager fetching to be specified as a member of the
javax.persistence.FetchType enumeration.
Listing 6-15. Mapping a One-to-Many Relationship from the Book Entity to the Publisher Entity
@OneToMany(cascade = ALL,mappedBy = "publisher")
public Set<Book> getBooks() {
return books;
}
The many-to-one end of this relationship is expressed in similar terms to the one-to-
many end, as shown in Listing 6-16.
Search WWH ::




Custom Search