我有一個實體類,它使用兩個字段作爲主鍵(在一起)。這是我正在嘗試的。我已經有了數據庫,所以我不能停止按照這個路徑創建一個主鍵。在休眠中使用兩個字段作爲唯一ID
@Entity
public class Account {
private String description;
private AccountPk id;
public Account (String description) {
this.description = description;
}
protected Account() {
}
@EmbeddedId
public AccountPk getId() {
return this.id;
}
public String getDescription() {
return this.description;
}
public void setId(AccountPk id) {
this.id = id;
}
public void setDescription(String description) {
this.description = description;
}
}
然後,我有另一種支持類
public class AccountPk {
private String code;
private Integer number;
public AccountPk() {
}
public String getCode() {
return this.code;
}
public Integer getNumber() {
return this.number;
}
public void setNumber(Integer number) {
this.number = number;
}
public void setCode(String code) {
this.code = code;
}
public int hashCode() {
int hashCode = 0;
if(code != null) hashCode ^= code.hashCode();
if(number != null) hashCode ^= number.hashCode();
return hashCode;
}
public boolean equals(Object obj) {
if(!(obj instanceof AccountPk)) return false;
AccountPk target = (AccountPk)obj;
return ((this.code == null) ?
(target.code == null) :
this.code.equals(target.code))
&& ((this.number == null) ?
(target.number == null) :
this.number.equals(target.number));
}
}
什麼我有一個問題是映射器類,Account.hbm.xml它看起來像
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class
name="hello.Account"
table="MESSAGES">
<id
name="id"
column="MESSAGE_ID">
<generator class="increment"/>
</id>
<property
name="description"
column="DESCRIPTION"/>
</class>
</hibernate-mapping>
我我確信這個XML文件是罪魁禍首,但我不知道如何以正確的方式做到這一點。所以,我會感謝你的幫助。
我覺得這篇文章可以幫助: http://stackoverflow.com/ question/6405746/mapping-manytomany-with-composite-primary-key-and-annotation –