我有数据库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