Java Persistence/OneToMany

From Wikibooks, the open-content textbooks collection

< Java Persistence
Jump to: navigation, search

A one to many relationship in Java is where the source object has an attribute that stores a collection of target objects and (if) those target objects had the inverse relationship back to the source object it would be a many to one relationship. All relationships in Java and JPA are unidirectional, in that if a source object references a target object there is no guarantee that the target object also has a relationship to the source object. This is different than a relational database, in which relationships are defined through foreign keys and querying such that the inverse query always exists.

JPA also defines a many to many relationship, which is similar to a one to many relationship except that the inverse relationship (if it were defined) is a many to many relationship. The main difference between a one to many and a many to many relationship in JPA is that a many to many always makes use of a intermediate relational join table to store the relationship, where as a one to many can either use a join table, or a foreign key in target object's table referencing the source object table's primary key. If the one to many uses a foreign key in the target object's table JPA requires that the relationship be bi-directional (inverse many to one relationship must be defined in the target object), and the source object must use the mappedBy attribute to define the mapping.

In JPA a one to many relationship is defined through the @OneToMany annotation or the <one-to-many> element.

An example of OneToMany relationship:

 @Entity
 public class Assignment {
 @Id
 public int Id;
 @ManyToOne
 public Student st;
 }
 @Entity
 public class Student {
 @Id
 public int Id;
 @OneToMany(mappedBy="st")
 Set<Assignment> assignments;
 }

Will be represented in the database by:

Assignment table:

ASSIGNMENT
ID ST_ID

Student table:

STUDENT
ID ...


with ST_ID the foreign key to student table.

Personal tools
Create a book
  • Add wiki page
  • Collections help