Object equality by natural key
Defining entity equality based on database identity suffers from a severe deficiency: Newly created instances invariably differ from any foreign non-identical instance regardless whether it does have a database identity or not. We consider an example:
package session2; ... public class CompareNewlyCreated { ... // Create two transient instances final User a = new User(123, "goik", "Martin Goik"), ❶ b = new User(123, "goik", "Martin Goik"); ❷ System.out.println("a.equals(b):" + a.equals(b)); ❸ { final Session session = HibernateUtil.createSessionFactory("session2/hibernate.cfg.xml").openSession(); final Transaction transaction = session.beginTransaction(); // previously saved as new User(123, "goik", "Martin Goik"); final User user = (User) session.load(User.class, 1L); ❹ System.out.println("a.equals(user)):" + a.equals(user)); ❺ transaction.commit(); session.close(); } ...
Create two transient instances being identical by value. |
|
Both instances are defined to differ by value. |
|
Load a persistent entity from the database. |
|
Transient and persistent instances are defined to differ by value. |
Apparently this is definitely wrong: We do have unique
database index definitions. All objects in question do have common
values 123 and "goik"
on these respective keys.