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