有三種作法,特色 annotation 分別為 @EmbeddedId、@Id 與 @IdClass。
- @EmbeddedId 是建議的作法。
- @Id 不是標準,只有 Hibernate 支援。
- @IdClass 是 EJB 年代的東西。
生命有限,只看建議的作法。
先將 PK 需要的欄位抽出獨立成一個 @Embeddable class。
@Embeddable
@SuppressWarnings("serial")
public class SorderId implements Serializable {
private String clazz;
private String no;
@Column(name = "O_CLASS")
public String getClazz() {
return this.clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
@Column(name = "O_NO")
public String getNo() {
return this.no;
}
public void setNo(String no) {
this.no = no;
}
}
然後在 Entity 裡使用 @EmbeddedId。@Entity(name = "ORDERS")
@SuppressWarnings("serial")
public class Sorder implements Serializable {
private SorderId id;
// ...
@EmbeddedId
@AttributeOverride(...)
public SorderId getId() {
return this.id;
}
public void setId(SorderId id) {
this.id = id;
}
// ....
}
其實和 @Embeddable 與 @Embedded 非常雷同,只是將 @Embedded 換成 @EmbeddedId,其他都一樣,也可以使用 @AttributeOverride。收工!
---
---
---
沒有留言:
張貼留言