Java Persistence/ManyToOne

From Wikibooks, the open-content textbooks collection

< Java Persistence
Jump to: navigation, search

A many to one relationship in Java is where the source object has an attribute that references another target object and (if) that target object had the inverse relationship back to the source object it would also be a one to many 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 one to one relationship, which is similar to a many to one relationship except that the inverse relationship (if it were defined) is a one to one relationship. The main difference between a one to one and a many to one relationship in JPA is that a many to one always contains a foreign key from the source object's table to the target object's table, where as a one to one relationship the foreign key may either be in the source object's table or the target object's table.

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

An example of ManyToOne relationship:

 @Entity
 public class Assignment {
 @Id
 public int Id;
 @ManyToOne
 public Student st;
 }

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