简体   繁体   中英

Always use a UUID for the id property of JPA entities and base equals and hashcode on it?

There are a lot of articles that cover how to implement hashcode and equals for JPA entities.

Instead of worrying about this for every single JPA entity created, would it be simpler to set a final and updatable = false id property to a UUID and base the hashcode and equals implementations on that id? Any drawbacks to doing it this way?

Why add a new extra column or use UUID which does not play well with MySQL clustered indexes when you can implement equals and hashCode based on the AUTO_INCREMENTED or SEQUENCE-based Primary Key?

So, this is how your implementations would look like:

@Entity
public class Book implements Identifiable<Long> {
 
    @Id
    @GeneratedValue
    private Long id;
 
    private String title;
 
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Book)) return false;
        Book book = (Book) o;
        return getId() != null && Objects.equals(getId(), book.getId());
    }
 
    @Override
    public int hashCode() {
        return getClass().hashCode();
    }
 
    //Getters and setters omitted for brevity
}

The constant getClass().hashCode() value is for making sure it is consistent across all entity state transitions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM