jakarta.persistence.OneToMany
- Implemented Interfaces:
Annotation
- Target:
- Method, Field
If the collection is defined using generics to specify the element type, the associated target entity type need not be specified; otherwise the target entity class must be specified. If the relationship is bidirectional, the mappedBy element must be used to specify the relationship field or property of the entity that is the owner of the relationship.
A OneToMany association usually maps a foreign key column or columns in the table of the associated entity. This mapping may be specified using the JoinColumn annotation. Alternatively, a unidirectional OneToMany association is sometimes mapped to a join table using the JoinTable annotation.
The OneToMany annotation may be used within an embeddable class contained within an entity class to specify a relationship to a collection of entities. If the relationship is bidirectional, the mappedBy element must be used to specify the relationship field or property of the entity that is the owner of the relationship.
When the collection is a Map<K,V>, the cascade element and the orphanRemoval element apply to the map value.
Example 1: One-to-Many association using generics
// In Customer class: @OneToMany(cascade = ALL, mappedBy = "customer") public Set getOrders() { return orders; } // In Order class: @ManyToOne @JoinColumn(name = "CUST_ID", nullable = false) public Customer getCustomer() { return customer; }
Example 2: One-to-Many association without using generics
// In Customer class: @OneToMany(targetEntity = com.acme.Order.class, cascade = ALL, mappedBy = "customer") public Set getOrders() { return orders; } // In Order class: @ManyToOne @JoinColumn(name = "CUST_ID", nullable = false) public Customer getCustomer() { return customer; }
Example 3: Unidirectional One-to-Many association using a foreign key mapping
// In Customer class: @OneToMany(orphanRemoval = true) @JoinColumn(name = "CUST_ID") // join column is in table for Order public Set getOrders() { return orders; }
- Since:
- Jakarta Persistence (JPA) 1.0
Annotation Elements
Class<?> targetEntityDefaults to the parameterized type of the collection when defined using generics.
- Default:
void/class
- Since:
- Jakarta Persistence (JPA) 1.0
Defaults to no operations being cascaded.
When the target collection is a Map<K,V>, the cascade element applies to the map value.
- Default:
- {}
- Since:
- Jakarta Persistence (JPA) 1.0
- Default:
FetchType.LAZY
- Since:
- Jakarta Persistence (JPA) 1.0
String mappedBy- Default:
- ""
- Since:
- Jakarta Persistence (JPA) 1.0
boolean orphanRemoval- Default:
- false
- Since:
- Jakarta Persistence (JPA) 2.0
Additional JDK methods inherited from java.lang.annotation.Annotation
annotationType(), equals(Object), hashCode(), toString()