JPA Mapping two Tables in one Class

2

Posted on June 1, 2011 by

Share it now!

THERE IS A NEW VERSION OF THIS POST.
CLICK HERE: http://uaihebert.com/?p=1674&page=11

Hello, good evening.

We will see today how to map two tables in one class. We will see a simple approach to get this task done.

If you want to run the code that I will post here, you can see in the older posts how to set up your application; there you will find the download link and the step-by-step of how to set up your application. The others JPA posts are (starting from the newest to the oldest): Mapping Date and Enum, Composite Primary-Key, SequenceGenerator, TableGenerator – Simple Primay Key, Auto Create Schema Script with: Ant, Hibernate 3 and JPA 2, Tutorial Hibernate 3 with JPA 2.

I will be using the Postgres database, and I will post here a SQL script to create the tables and the needed records. If you have any doubts about how to set up your application (e.g. persistence.xml, libraries, build path) check out the older posts about this subjects. I will post here just the needed data to this post.

CREATE TABLE hello.person
(
  id integer NOT NULL,
  "name" character varying(255) NOT NULL
)
WITH (
  OIDS=FALSE
);
ALTER TABLE hello.person OWNER TO postgres;

CREATE TABLE hello.health_care
(
  id integer NOT NULL,
  "company_name" character varying(255)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE hello.health_care OWNER TO postgres;

-- Insert a person and his healt care company
INSERT INTO hello.person values (1 , 'john');
INSERT INTO hello.health_care values ( 1, 'best ever');

It will be a simple case, a person that has a health care. Let us suppose that this health care is not controlled by your application, but for another application of your company.

In our case, we will not create a HealthCare class because it has one field only, the health care company name; the system architects decided to only add this field to the Person class.

Let us see how our Person class will be:

package com;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;

@Entity
@Table(name = "person")
@SecondaryTable(name = "health_care", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "id") })
public class Person {

    @Id
    private int id;

    @Column
    private String name;

    @Column(table = "health_care", name = "company_name")
    private String companyName;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

About the Person class:

  • The @SecondaryTable annotation “tells” to the JPA that there is another table with some data of the Person class.
  • The parameter pkJoinColumns of the @SecondaryTable annotation it is used to indicate which column the JPA will use as relationship. We did not indicate any field in the @SecondaryTable annotation to specify the relationship between the tables person and health_care; the JPA by default will match the person table ID with the health_care id ([person]id == [health_care]id).
  • In the @Column annotation of the “companyName” attribute, we notify the JPA in which table it will find attribute value through the “table” parameter.

I will write bellow, a code that will find our record Person in the database:

package com;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Main {

    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("Hello");
        EntityManager em = emf.createEntityManager();

        try {
            em.getTransaction().begin();

            Person person = em.find(Person.class, 1);

            System.out.println(person.getName());
            System.out.println(person.getCompanyName());

            em.getTransaction().commit();
        }
        catch (Exception e) {
            em.getTransaction().rollback();
            e.printStackTrace();
        }
        finally{
            emf.close();
        }

        System.out.println("It is over");
    }
}

Run the main class code and check the result:

Console Image.

Notice that the company name came as it were part of the Person class.

Do you have any question/suggestion?

Just post it.

See you later.

Response to JPA Mapping two Tables in one Class

  1. sokal

    hi,
    thanks for tutoraial.
    i need additional help.
    i have 3 table.
    1 parent TAble.
    2 child TABLE
    how I am able to send data from one class. parent as well as child class. using JPA Eclipse-link

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current day month ye@r *