javaspringspring-bootspring-data-jpahibernate-entitymanager

Does JPA Entity store reference to Entity Manager?


@Entity
class Employee{
@Id
String name;
int age;
String gender;
}

I'm using the above entity object as key in Hashmap:

Employee e1 = new Employee("abc",23,"M")

Now if I create a new entity with same id and persist it:

@Autowired
EmployeeDao employeeDao;

e1.findByName("abc");

Map<Employee, Boolean> map = new HashMap<>();
map.put(e1, true);

Employee e2 = new Employee("abc",45,"F");
employeeDao.save(e2)

for(Employee ex:map.keySet()){
     map.get(ex);   //Returns null
}

I figure out my HashKey(e1) is also changed(to e2). Now since Hashmap uses "Entry" objects where Key would be an Employee Entity object(Which got changed), is it that JPA entities references objects stored in Entity manager? Is this why the Key changed?

Why did the Key(e1) change automatically?


Solution

  • Spring Data JPAs save does a merge under the hood. The merge looks for an entity with the same class and id in the 1st level cache. If it finds one it copies the state from the argument over to the instance in the cache. Dirty checking then ensures it gets flushed to the database. merge and in turn save also return the entity that was found in the 1st level cache.

    Since you loaded e1 from the database in the same transaction it is in the 1st level cache and gets modified.