Essential object-relational mapping in JPA


The Java Persistence API is the standard framework for persistence in both Java SE and Java EE platforms. It is the outcome of the collaborative work of the industry’s leading vendors in object-relational mapping, EJB and JDO, including a remarkable contribution from the open source community.

In this post we summarize, one-by-one, the essential relationships between entities. We examine each relationship from the prespectives of “Domain Model” and “Relation Model”, and provide the associated construction in JPA. Finally, for each relationship we present an example from the real world.

The relationships are divided in two categories. “For daily use” presents the correct way to use common relationships in our application development activities. On the other hand, “Containing pitfalls” identify common mistakes.

For daily use:

  1. One-to-One (one direction)
  2. One-to-One (both directions)
  3. Many-to-One (one direction)
  4. Many-to-One (both directions)
  5. One-to-Many (one direction)
  6. One-to-Many (both directions)
  7. Many-to-Many (both directions)

Containing pitfalls:

  1. Many-to-Many (one direction)

One-to-One (one direction)

Domain model of an one-to-one unidirectional relationship

Domain model of an one-to-one unidirectional relationship

@Entity
class A {
   @Id int id;

   @OneToOne
   B b;
}

@Entity
class B {
   @Id int id;
}
Relation model of an one-to-one unidirectional relationship

Relation model of an one-to-one unidirectional relationship

Example 1, One-to-One unidirectional relationship in JPA

An employee has one desk.

@Entity
public class Employee implements Serializable {

   @Id 
   private int id;

   private String name;

   @OneToOne
   private Desk desk;

}

@Entity
public class Desk implements Serializable {

   @Id 
   private int id;

   private String position;  

}
Physical description of an one-to-one unidirectional relationship

Physical description of an one-to-one unidirectional relationship

ER diagram of an one-to-one unidirectional relationship

ER diagram of an one-to-one unidirectional relationship

One-to-One (both directions)

Domain model of an one-to-one birectional relationship

Domain model of an one-to-one birectional relationship

In this case we would like to keep a reference between both sides.

@Entity
class A {
   @Id int id;

   @OneToOne
   B b;
}

@Entity
class B {
   @Id int id;

   @OneToOne(mappedBy="b")
   A a;
}
Relation model of an one-to-one bidirectional relationship

Relation model of an one-to-one bidirectional relationship

Since the relation concerns both directions, we may change the owning side.

@Entity
class A {
   @Id int id;

   @OneToOne(mappedBy="a")
   B b;
}

@Entity
class B {
   @Id int id;

   @OneToOne
   A a;
}
Relation model of an one-to-one bidirectional relationship

Relation model of an one-to-one bidirectional relationship

Example 2, One-to-One bidirectional relationship in JPA

A husband has exactly one wife. A wife has exactly one husband.

@Entity
public class Husband implements Serializable {

   @Id
   private int id;

   private String name;

   @OneToOne
   private Wife wife;

}

@Entity
public class Wife implements Serializable {

   @Id
   private int id;

   private String name;

   @OneToOne(mappedBy="wife")
   private Husband husband;

}

We assume husband is the owning side, so he will hold the foreign key.

Physical description of bidirectional one-to-one relationship

Physical description of an one-to-one bidirectional relationship

ER diagram of an one-to-one bidirection relationship

ER diagram of a bidirection one-to-one relationship

Now we can ask the wife “Who is your husband?”, as well as, ask the husband “Who is your wife?”.

Many-to-One (one direction)

Domain model of a many-to-one unidirectional relationship

Domain model of a many-to-one unidirectional relationship

@Entity
class A {
   @Id int id;

   @ManyToOne
   B b;
}

@Entity
class B {
   @Id int id;
}
Relation model of a many-to-one unidirectional relationship

Relation model of a many-to-one unidirectional relationship

Example 3, Many-to-One unidirectional relationship in JPA

There are millions of music fans out there. Each fan has his favorite singer. Of course, a signer is not able to keep detailed records of his fans.

@Entity
public class Fan implements Serializable {

   @Id
   private int id;

   private String name;

   @ManyToOne
   private Singer favoriteSinger;

}

@Entity
public class Singer implements Serializable {

   @Id
   private int id;

   private String name;

}

As a result, the foreign key goes to the fan.

Physical description of a many-to-one unidirectional relationship

Physical description of a many-to-one unidirectional relationship

ER diagram of a many-to-one unidirectional relationship

ER diagram of a many-to-one unidirectional relationship

Now we may ask any fan “Who is your favorite signer?”.

Many-to-One (both directions)

Domain model of a many-to-one bidirectional relationship

Domain model of a many-to-one bidirectional relationship

@Entity
class A {
   @Id int id;

   @ManyToOne
   B b;
}

@Entity
class B {
   @Id int id;

   @OneToMany(mappedBy="b")
   Collection<A> listOfA;
}
Relation model of a many-to-one bidirectional relationship

Relation model of a many-to-one bidirectional relationship

Example 4, Many-to-One bidirectional relationship in JPA

The children of a father: A child knows his father and the father knows his children.

@Entity
public class Child implements Serializable {

   @Id
   private int id;

   private String name;

   @ManyToOne
   private Father father;

}

@Entity
public class Father implements Serializable {

   @Id
   private int id;

   private String surname;

   @OneToMany(mappedBy="father")
   private Collection<Child> children;

}
Physical description of a many-to-one bidirectional relationship

Physical description of a many-to-one bidirectional relationship

ER diagram of a many-to-one bidirectional relationship

ER diagram of a many-to-one bidirectional relationship

One-to-Many (one direction)

Domain model of a one-to-many unidirectional relationship

Domain model of a one-to-many unidirectional relationship

It is the case when an entity has a set of characteristics.

@Entity
class A {
   @Id int id;

   // A join table is assumed.
   @OneToMany
   Collection<B> listOfB;
}

@Entity
class B {
   @Id int id;
}
Relation model of a one-to-many unidirectional relationship

Relation model of a one-to-many unidirectional relationship

Thus, when declaring an OneToMany annotation without a mappedBy element, then a join table is assumed.

Example 5, One-to-Many unidirectional relationship in JPA

A library which provides facilities.

@Entity
public class Library implements Serializable {

   @Id
   private int id;

   private String name;

   @OneToMany
   private Collection<Facility> facilities;

}

@Entity
public class Facility implements Serializable {

   @Id
   private String code;

   private String description;

}
Physical description of a one-to-many unidirectional relationship

Physical description of a one-to-many unidirectional relationship

ER diagram of an one-to-many unidirectional relationship

ER diagram of an one-to-many unidirectional relationship

Now we can ask a library “What facilities do you provide?”. The answer could be “Scanning, Printing and Photocopying”. This set of facilities may be provided by one or more libraries at the same time.

If using a join table is not what you want, then you should use the next relationship.

One-to-Many (both directions)

It is exactly the same with Many-to-One (both directions), looking via a mirror.

Domain model of a one-to-many bidirectional relationship

Domain model of a one-to-many bidirectional relationship

@Entity
class A {
   @Id int id;

   @OneToMany(mappedBy="a")
   Collection<B> listOfB;
}

@Entity
class B {
   @Id int id;

   @ManyToOne
   A a;
}
Relation model of an one-to-many bidirectional relationship

Relation model of an one-to-many bidirectional relationship

Example 6, One-to-Many bidirectional relationship in JPA

A manager who manages projects.

@Entity
public class Manager implements Serializable {

   @Id
   private int id;

   private String name;

   @OneToMany(mappedBy="manager")
   private Collection<Project> projects;

}

@Entity
public class Project implements Serializable {

   @Id
   private int id;

   private String title;

   @ManyToOne
   private Manager manager;

}
Physical description of a one-to-many bidirectional relationship

Physical description of a one-to-many bidirectional relationship

ER diagram of an one-to-many bidirectional relationship

ER diagram of an one-to-many bidirectional relationship

Many-to-Many (both directions)

Domain model of a many-to-many bidirectional relationship

Domain model of a many-to-many bidirectional relationship

@Entity
class A {
   @Id int id;

   @ManyToMany
   Collection<B> listOfB;
}

@Entity
class B {
   @Id
   int id;

   @ManyToMany(mappedBy="listOfB")
   Collection listOfA; } 

Of course, a join table is used.

Relation model of a many-to-many bidirectional relationship

Relation model of a many-to-many bidirectional relationship

Note: In a birectional many-to-many relationship we should always include the mappedBy element to either of the sides. This ensures that exactly one join table is used.

Example 7, Many-to-Many bidirectional relationship in JPA

An engineer works in many projects. A project occupies many engineers. This is a classic many-to-many relationship. Moreover it expands to both directions, as:

  • An engineer should in which projects he is working.
  • The project should know the engineers it occupies.
@Entity
public class Engineer implements Serializable {

   @Id
   private int id;

   private String name;

   @ManyToMany
   @JoinTable(name="ENGINEER_PROJECT",  
              joinColumns=@JoinColumn(name="ENGINEER_ID"), 
              inverseJoinColumns=@JoinColumn(name="PROJECT_ID"))
   private Collection<Project> projects;

}

@Entity
public class Project implements Serializable {

   @Id
   private int id;

   private String title;

   @ManyToMany(mappedBy="projects")
   private Collection<Engineer> engineers;

}
Physical description of a many-to-many bidirectional relationship

Physical description of a many-to-many bidirectional relationship

ER diagram of a many-to-many bidirectional relationship

ER diagram of a many-to-many bidirectional relationship

Pitfall: Many-to-Many (one direction)

Not specifying the mappedBy element in a many-to-many relationship, assumes two join tables and should be avoided.

@Entity
class A {
   @Id int id;

   @ManyToMany
   Collection<B> listOfB;
}

@Entity
class B {
   @Id int id;

   @ManyToMany
   Collection<A> listOfA;
}

The same happens when the ManyToMany annotation is ommitted on one side.

@Entity
class A {
   @Id int id;

   @ManyToMany
   Collection<B> listOfB;
}

@Entity
class B {
   @Id int id;

   Collection<A> listOfA;
}
Relation model of two many-to-many unidirectional relationship

Relation model of two many-to-many unidirectional relationship

To avoid this pitfall, I would follow the instructions of Many-to-Many (both directions) relationship.

Notes

  1. The drawings were created using OpenOffice.org Draw 3.3.0
  2. The console output of the examples is from MySQL 5.5 Command Line Client
  3. The EER diagrams of the examples were created using MySQL Workbench 5.2.34 CE, Revision 7780

References

  • M. Keith, M. Schincariol, “Pro JPA 2: Mastering the Java™ Persistence API”, Apress, United States of America, 2009.

15 Responses to Essential object-relational mapping in JPA

  1. can says:

    awesome?

  2. gilson says:

    wow, it’s fantastic post!

  3. Very good tutorial. Really explains very well all of the relational mappings in JPA. Recommended reading!

    Brett

  4. Hai says:

    Nikos, this is great! thanks a lot for you sharing! However, one scenario you missed — how to handle extra columns in the join table? for example, join table engineer_project has one extra column: have_or_notHave, engineer_id, project_id. have_or_notHaveis to say: project has this enginer or not has this enginer. even this column doesn’t make real sense, just talking about JPA, what’s your idea about extra column in join table?

    Thanks,
    Hai

  5. thilanka says:

    simplest relational mapping example ever

  6. Vlad says:

    Great work man!!

  7. Reader says:

    cannot believe jpa annotations is so simple (of course author presented in excellent manner). good bye hibernate xml settings.

  8. kingCrawlerx says:

    this post is SO good. I’m going to share it with my classmates. thanks for your work

  9. About Java says:

    awesome article.. clear steps of object-relational mapping in JPA..🙂

  10. vin says:

    Wow !! Excellent Posting

  11. Sonu Singh says:

    It is very simple and helpful relational mapping.
    Thank you Nikos.

  12. Dhinakaran says:

    Really great tutorial for beginners…Expecting other good & easy tutorial like this.

  13. Amine says:

    very sample code and perfuct (Y), thank you (Y)

  14. Smith says:

    wow is this so simple …… too good ….. thnx for posting ….

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: