Hibernate itself identifies rows from a table by their primary keys, following the principles of relational theory as developed by Edgar Codd in the 1960s. Today the id is typically generated automatically by Hibernate and the database engine.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity | |
@Table(name = "MY_TABLE") | |
public class MyTable extends AbstractEntity { | |
@Id | |
@GeneratedValue(strategy = GenerationType.AUTO) | |
private Long id; | |
private String value1; | |
private String value2; | |
... | |
public boolean equals(Object obj) { | |
if (obj == null || !(obj.getClass().equals(this.getClass()))) { | |
return false; | |
} | |
return getId().equals(((GenericEntity ) obj).getId()); | |
} | |
} |
A new theory says that an entity's equals method should not compare ids but should compare all attributes other than the id, i.e. value1 and value2 in the example above.
Arguments FOR comparing attributes other than the id
- When creating new entities, the entity has no id assigned before it is saved to database, so the id cannot be used to determine identity.
- It is the various attribute values, not the id, that make up the significance of any row of data.
A. Differences would typically be encountered fairly rapidly making the additional processing negligible.
Arguments AGAINST comparing attributes other than the id
- Hibernate lazy initialization can be triggered by a comparison after the Hibernate session has ended. Scenarios include cached entities.
- Regardless of identical attribute values, if the ids are different then there are separate rows in the database.
- The comparing of ids parallels relational theory, a central principle for all relational databases, also paralleled by Hibernate.
Bottom line
The Hibernate entity equals method should compare IDs.
No comments:
Post a Comment