JPA Tutorial - JPA EmbeddedID Example








The following code shows how to use the class as an Embedded Id.

First it creates a Embeddable entity.

@Embeddable
public class ProfessorId implements Serializable{
  private String country;

  @Column(name = "EMP_ID")
  private int id;

It marks the ProfessorId with @EmbeddedId annotation.

@Entity
public class Professor {
  @EmbeddedId
  private ProfessorId id;




Example

The following code is from Professor.java.

package com.java2s.common;

import javax.persistence.EmbeddedId;
import javax.persistence.Entity;

@Entity
public class Professor {
  @EmbeddedId
  private ProfessorId id;

  private String name;

  private long salary;

  public Professor() {
  }

  public Professor(String country, int id) {
    this.id = new ProfessorId(country, id);
  }

  public int getId() {
    return id.getId();
  }

  public String getCountry() {
    return id.getCountry();
  }

  public String getName() {
    return name;
  }

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

  public long getSalary() {
    return salary;
  }

  public void setSalary(long salary) {
    this.salary = salary;
  }

  public String toString() {
    return "Professor id: " + getId() + " name: " + getName() + " country: " + getCountry();
  }
}

The following code is from ProfessorId.java.

package com.java2s.common;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class ProfessorId implements Serializable{
  private String country;

  @Column(name = "EMP_ID")
  private int id;

  public ProfessorId() {
  }

  public ProfessorId(String country, int id) {
    this.country = country;
    this.id = id;
  }

  public String getCountry() {
    return country;
  }

  public int getId() {
    return id;
  }

  public boolean equals(Object o) {
    return ((o instanceof ProfessorId) && country.equals(((ProfessorId) o).getCountry()) && id == ((ProfessorId) o)
        .getId());

  }

  public int hashCode() {
    return country.hashCode() + id;
  }
}

The following code is from PersonDaoImpl.java.

package com.java2s.common;


import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

@Transactional
public class PersonDaoImpl {
  public void test(){
    
    Professor emp = new Professor("US", 1);
    emp.setName("Tom");
    emp.setSalary(1);
    em.persist(emp);
  }
  @PersistenceContext
  private EntityManager em;
}


Download EmbeddedID.zip

The following is the database dump.

Table Name: PROFESSOR
 Row:
    Column Name: COUNTRY,
    Column Type: VARCHAR:
    Column Value: US

    Column Name: EMP_ID,
    Column Type: INTEGER:
    Column Value: 1

    Column Name: NAME,
    Column Type: VARCHAR:
    Column Value: Tom

    Column Name: SALARY,
    Column Type: BIGINT:
    Column Value: 1