JPA 嵌入式ID示例

JPA教程 – JPA 嵌入式ID示例

以下代码显示了如何将类用作嵌入式ID。

首先它创建一个Embeddable实体。

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

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

它用 @EmbeddedId 注释标记 ProfessorId

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

例子

以下代码来自Professor.java。

package cn.w3cschool.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();
  }
}

以下代码来自ProfessorId.java。

package cn.w3cschool.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;
  }
}

下面的代码来自PersonDaoImpl.java。

package cn.w3cschool.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;
}

下载 EmbeddedID.zip

以下是数据库转储。

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
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《JPA 嵌入式ID示例》
文章链接:https://zhuji.vsping.com/293477.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。