W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
以下代碼顯示了如何將類用作嵌入式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
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: