JPA 嵌入式ID示例

2018-02-23 15:56 更新

JPA教程 - JPA 嵌入式ID示例


以下代碼顯示了如何將類用作嵌入式ID。

首先它創(chuàng)建一個(gè)Embeddable實(shí)體。

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

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

它用 @EmbeddedId 注釋標(biāo)記 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

以下是數(shù)據(jù)庫轉(zhuǎn)儲(chǔ)。

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


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)