JPA one to many mapping

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Hello, Previously we have seen one to one mapping. This article will explain jpa one to many relationship.

JPA one to many mapping:

We have learned about many to one mapping. JPA one to many mapping is just the reverse of it. Taking the same example, i.e. multiple Employee entities belong to one department. We can say it that a Department entity can contain multiple Employee entities. The database structure is as follows:

  • Employee table has primary key idemployee;
  • Employee table has a foreign key named iddepartment which references department primary key
  • This means Employee has the ownership of Department

ManyToOneDatabase

Employee entity

 Department entity

You can notice the jpa one to many mapping annotation:

This means a Department has multiple Employee entities. The mappedBy element references the department field in Employee entity. This makes it a bidirectional Many to One mapping with respect to Employee entity.

There are two points to remember about jpa one to many mapping:

  • The many to one side is the owning side of relationship. The column is defined on that side.
  • The one to many mapping is the inverse side side so the mappedBy element must be used on the inverse side.

You can test it using

I hope this helps understand the jpa one to many mapping. Please feel free to suggest any improvements.

 

References for further study :

 

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

4 thoughts on “JPA one to many mapping

  • Pingback:JPA many to many mapping | theJavaGeek

  • November 16, 2015 at 4:00 pm
    Permalink

    Hello Prasad Kharkar.
    Firstly thank you very much for docs.It is very usefull for me.
    I have a question;
    What is the association between id_gen table and our main tables. I mean how can we connect iddepartment and id_gen tables or its columns??

    Reply
  • November 29, 2015 at 7:25 pm
    Permalink

    please insert the output also then only we come to know how the program is working..

    Reply
    • November 30, 2015 at 9:34 am
      Permalink

      Hi Guruprasad, thank you for comment. I may not have attached output while learning but the program definitely works. I write articles only after it works successfully.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *