- Collection mappings include OneToMany, ManyToMany,
- JPA requires that the type of the collection field or get/set methods be one of the Java collection interfaces,
Collection
,List
,Set
, orMap
.
Collection Implementations
- Your field should not be of a collection implementation type, such as
ArrayList
.
Duplicates
- A
List
in Java supports duplicate entries, and aSet
does not. - In the database, duplicates are generally not supported.
- Technically it could be possible if a
JoinTable
is used, but JPA does not require duplicates to be supported, and most providers do not. - If you require duplicate support, you may need to create an object that represents and maps to the join table. This object would still require a unique
Id
, such as aGeneratedValue
.
Ordering
- JPA allows the collection values to be ordered by the database when retrieved.
- This is done through the
@OrderBy
annotation or<order-by>
XML element. - The value of the
OrderBy
is a JPQLORDER BY
string. - Attribute name followed by
ASC
orDESC
for ascending or descending ordering. - If no
OrderBy
value is given it is assumed to be theId
of the target object. - The
OrderBy
value must be a mapped attribute of the target object. - Using an
OrderBy
does not ensure the collection is ordered in memory.You are responsible for adding to the collection in the correct order. - Java does define a
SortedSet
interface andTreeSet
collection implementation that does maintain an order. - You can also use the
Collections.sort()
method to sort aList
when required.
Example of a collection order by annotation
@Entity public class Employee { @Id private long id; ... @OneToMany @OrderBy("areaCode") private List<Phone> phones; ... }
The OrderColumn
is maintained by the mapping and should not be an attribute of the target object. The table for the OrderColumn
depends on the mapping. For a OneToMany
mapping it will be in the target object's table. For aManyToMany
mapping or a OneToMany
using a JoinTable
it will be in the join table. For an ElementCollection
mapping it will be in the target table.
Example of a collection order column database
EMPLOYEE (table)
ID FIRSTNAME LASTNAME SALARY
1 Bob Way 50000
2 Sarah Smith 60000
EMPLOYEE_PHONE (table)
EMPLOYEE_ID PHONE_ID INDEX
1 1 0
1 3 1
2 2 0
2 4 1
PHONE(table)
ID AREACODE NUMBER
1 613 792-7777
2 416 798-6666
3 613 792-9999
4 416 798-5555
Example of a collection order column annotation
@Entity
public class Employee {
@Id
private long id;
...
@OneToMany
@OrderColumn(name="INDEX")
private List<Phone> phones;
...
}
No comments:
Post a Comment