在hibernate中使用两个字段作为唯一id
我有一个实体类,它使用它的两个字段作为主键(一起)。这就是我正在尝试的。我已经有了数据库,所以我不能停止沿着这个路径创建一个主键在hibernate中使用两个字段作为唯一id,hibernate,nhibernate-configuration,Hibernate,Nhibernate Configuration,我有一个实体类,它使用它的两个字段作为主键(一起)。这就是我正在尝试的。我已经有了数据库,所以我不能停止沿着这个路径创建一个主键 @Entity public class Account { private String description; private AccountPk id; public Account (String description) { this.description = description; } prote
@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文件是罪魁祸首,但我不知道如何正确地处理它。因此,我将感谢您在这方面的帮助。使用
而不是
,例如:
<composite-id>
<key-property name="firstId" column="FIRST_ID_COL" type="..." />
<key-property name="secondId" column="SECOND_ID_COL" type="..." />
</composite-id>
顺便说一下,您不能使用具有复合id的生成器。您必须自己生成id。(无论如何,复合键的生成器通常没有意义。它应该生成哪些关键组件以及何时生成?我认为这篇文章会有所帮助:感谢各位的回复,但正如我已经阅读的内容所理解的,复合键是指两个或多个实体之间存在基数关系。此外,在我的实体上没有可以使用的“@CompositeId”注释?在我的例子中,只有一个表的两列中不应该有相同的数据组合。“@EmbeddedId”方法被hibernate社区的许多人认为是一种好方法;只有我知道如何配置它。
composite id>
当主键由两列或更多列组成时,您始终可以使用它。不一定存在基数关系不要问我注释的事,我从不使用它们,但你可能会找到一些信息。Xml映射文件似乎是更简单的解决方案。