主鍵類:定義為@Embeddable
@Embeddable
public class F {
private int id;
private int id2;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getId2() {
return id2;
}
public void setId2(int id2) {
this.id2 = id2;
}
}
持久化類:
@Entity
@Table(name="E_USER",uniqueConstraints={
@UniqueConstraint(columnNames={"yahoo"})
})
@IdClass(F.class)//將F作為主鍵類
public class User {
private int id;
private int id2;
//id id2必須和F中的屬性一致
private String yahoo;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId2() {
return id2;
}
public void setId2(int id2) {
this.id2 = id2;
}
public String getYahoo() {
return yahoo;
}
public void setYahoo(String yahoo) {
this.yahoo = yahoo;
}
}
最終生成sql:(MySQL)
create table E_USER (id integer not null, id2 integer not null, yahoo varchar(255), primary key (id, id2), unique (yahoo))