Java – hibernate composite key
Is it necessary to map the composite ID to the class?
Can you do this?
<composite-id> <key-property=..../> <key-property=..../> </composite-id>
Or should it be
<composite-id class=....> <key-property=..../> <key-property=..../> </composite-id>
If necessary, if we have composite keys, should this class implement the equals () and override () methods?
Solution
Hibernate needs to be able to compare and serialize identifiers Therefore, the identifier class must be serializable and override hashcode () and equals () in line with the concept of composite key equality in the database
If you map a composite ID to an entity's attribute, the entity itself is an identifier
The second method is called mapping composite identifiers, in which the identifier attribute named inside < composite ID > The element is duplicated on both the persistent class and the individual identifier class
Finally, composite - ID can be a component class In this case, the component class is an identifier class
Note that it is strongly recommended to use ID as a separate class Otherwise, you will only use session Get() or session The load () method of finding objects is very clumsy
Refer to relevant parts of the document:
> composite-id > Components as composite identifiers
In this example, the composite ID is mapped to an attribute of the entity (the following assumes that you are defining the Employee class)
<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() }
Mapped 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() }
Components as 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() }