我有數據庫revisions
和Pagu
休眠3複合鍵一個與GeneratedValue
在Pagu
模型這種雙表格,我必須複合鍵:
- ID INT(由數據庫自動生成的)
- revision_id(foreign_key to revision)表
如何在Hibernate 3上實現這個?
這就是我想出了
@Entity
@Table(name="pagu"
,schema="dbo"
,catalog="dbname"
)
@IdClass(PaguId.class)
public class Pagu implements java.io.Serializable {
private int id;
private int revisiId;
private Entitas entitas;
private Revisi revisi;
...
@Id
@GeneratedValue
@Column(name="id", unique=true, nullable=false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@Id
@Column(name="revisi_id", unique=true, nullable=false)
public int getRevisiId() {
return this.revisiId;
}
public void setRevisiId(int id) {
this.id = id;
}
這是我PaguId類
@Embeddable
public class PaguId implements java.io.Serializable {
private int id;
private int revisiId;
public PaguId() {
}
public PaguId(int id, int revisiId) {
this.id = id;
this.revisiId = revisiId;
}
@Column(name="id", nullable=false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="revisi_id", nullable=false)
public int getRevisiId() {
return this.revisiId;
}
public void setRevisiId(int revisiId) {
this.revisiId = revisiId;
}
public boolean equals(Object other) {
if ((this == other)) return true;
if ((other == null)) return false;
if (!(other instanceof PaguId)) return false;
PaguId castOther = (PaguId) other;
return (this.getId()==castOther.getId() && this.getRevisiId()==castOther.getRevisiId())
&& (this.getRevisiId()==castOther.getRevisiId());
}
public int hashCode() {
int result = 17;
result = 37 * result + this.getId();
result = 37 * result + this.getRevisiId();
return result;
}
}
當我試圖挽救這個在數據庫中,我得到了錯誤:
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session:
- 更新 - 但改變使用EmbeddedId的實現像這樣
public class Pagu implements java.io.Serializable {
private PaguId id;
...
@EmbeddedId
@AttributeOverrides({
@AttributeOverride(name="id", [email protected](name="id", nullable=false)),
@AttributeOverride(name="revisiId", [email protected](name="revisi_id", nullable=false)) })
public PaguId getId() {
return this.id;
}
public void setId(PaguId id) {
this.id = id;
}
....
它編譯正確,但給我錯誤時,堅持模型。
org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): id.model.Pagu
您不應該同時使用'@ Embeddable'和'@ IdClass'。可以選擇在實體類的複合主鍵類和'@ EmbeddedId'上使用:'@ Embeddable',或者2.在複合主鍵類和'@ IdClass'上沒有關於多個實體類級別的註釋實體類本身的「@ Id」註釋(用於字段)。 –
這樣做也會產生異常'具有相同標識符值的不同對象已經與會話相關聯:[id.go.model.Pagu#id.go..model.PaguId @ 5ae9]'如果有的話,我得到的那種錯誤是@id – ahmy
上的@GeneratedValue我找到了創建部分標識符生成的鏈接http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#d0e1150 但還有一個警告那麼您可能有興趣創建自己的ID生成機制,這樣的構造根本錯誤 – ahmy