java – hibernate复合键
作者:互联网
是否有必要将composite-id映射到类?
可以这样吗?
<composite-id>
<key-property=..../>
<key-property=..../>
</composite-id>
或应该是
<composite-id class=....>
<key-property=..../>
<key-property=..../>
</composite-id>
如果有必要,如果我们有复合键,那么该类应该实现equals()和override()方法?
解决方法:
Hibernate需要能够比较和序列化标识符.因此标识符类必须是可序列化的,并且与数据库的复合键相等概念一致地覆盖hashCode()和equals().
如果您将复合ID映射为实体的属性,则实体本身就是标识符.
第二种方法称为映射复合标识符,其中在< composite-id>内部命名的标识符属性.元素在持久化类和单独的标识符类上都是重复的
最后,composite-id可以是组件类.在这种情况下,组件类是标识符类.
请注意,强烈建议将ID作为单独的类.否则,您将只使用session.get()或session.load()查找对象的方法非常笨拙.
参考文档的相关部分:
> composite-id
> Components as composite identifiers
在此示例中,composite-id被映射为实体的属性. (以下假设您正在定义Employee类).
<composite-id>
<key-property name="EmployeeNumber"/>
<key-property name="Dependent"/>
</composite-id>
class EmployeeAssignment implements Serializable
{
string getEmployeeNumber()
void setEmployeeNumber( string value )
string getDepartment()
void setDepartment( string value )
boolean equals( Object obj )
int hashCode()
}
映射的composite-id:
<composite-id class="EmployeeAssignmentId" mapped="true">
<key-property name="EmployeeNumber"/>
<key-property name="Dependent"/>
</composite-id>
class EmployeeAssignment
{
string getEmployeeNumber()
void setEmployeeNumber( string value )
string getDepartment()
void setDepartment( string value )
}
class EmployeeAssignmentId implements Serializable
{
string getEmployeeNumber()
void setEmployeeNumber( string value )
string getDepartment()
void setDepartment( string value )
boolean equals( Object obj )
int hashCode()
}
作为composite-id的组件:
<composite-id name="Id" class="EmployeeAssignmentId">
<key-property name="EmployeeNumber"/>
<key-property name="Dependent"/>
</composite-id>
class EmployeeAssignment
{
EmployeeAssignmentId getId()
void setId( EmployeeAssignmentId value )
}
class EmployeeAssignmentId implements Serializable
{
string getEmployeeNumber()
void setEmployeeNumber( string value )
string getDepartment()
void setDepartment( string value )
boolean equals( Object obj )
int hashCode()
}
标签:composite-key,java,hibernate 来源: https://codeday.me/bug/20190919/1813212.html