I'm currently trying to persist data which I'd stored as a Map
in Java.
I've gotten this to work using List
already, however when I try to make this a Map
instead using @MapKeyEnumerated
and @MapKey
it acts a bit unexpected.
ExampleData.java
@MapKey(name = "feature")
@MapKeyEnumerated(EnumType.STRING)
@OneToMany(targetEntity = ExampleFeature.class, mappedBy = "exampleData")
private Map<Feature, ExampleFeature> features;
ExampleFeature.java
@ManyToOne
@JoinColumn(name = "example_id", nullable = false)
private ExampleData exampleData;
@Enumerated(EnumType.STRING)
@Column(name = "feature", nullable = false)
private Feature feature;
I'm able to add rows to the database manually outside of runtime, and when running the application it's able to load those entities correctly. All other entities are also working as intended.
When persisting entities in from the application, the ExampleFeature
does appear in the Map
, but all properties in the instance are the default Java values, and after stepping-out
Could anyone point me in the right direction as to what I might have wrong here?
The issue is that in the project, #save()
was only called on ExampleData
, but not on any of the relational properties under it. This means that Hibernate would try to persist the ExampleData
instance, however not any nested properties such as the EnumMap
.
The solution is to set cascade = CascadeType.ALL
which will tell Hibernate to persist changes in relational entities such as ExampleFeature
when persisting ExampleData
.
ExampleData.java
@MapKey(name = "feature")
@MapKeyEnumerated(EnumType.STRING)
@OneToMany(targetEntity = ExampleFeature.class, mappedBy = "exampleData", cascade = CascadeType.ALL)
private Map<Feature, ExampleFeature> features;