I believe I actually found a way to make this work a little better, i.e., forcing Hibernate (or whatever JPA provider) to have the key available before sticking objects in the collection. In this scenario, the object will be properly initialized and we can be sure that the business key won't be null.
For example, here's how the class EntityTwo
would have to look:
@Entity
@Table(name = "mytable2")
public class EntityTwo {
// other code omitted ...
@OneToMany(mappedBy = "entityTwo", fetch = FetchType.EAGER,
cascade = {CascadeType.ALL}, orphanRemoval = true)
@MapKey(name = "identifier")
private Map<String, EntityOne> entityOnes = new HashMap<>();
}
I haven't tested this specific code but I have other working examples and it should work fine according to the JPA docs. In this case, the JPA provider is cornered: it must know the value of identifier
before it can put the object in the collection. Besides, the object's hashCode
and equals
are not even called because the mapping is explicitly handled by the JPA provider.
This is a case in which explicitly forcing the tool to understand the way things are modeled and related to each other leads to great benefit.