简体   繁体   English

如何在 Hibernate/JPA 中持久化 EnumMap?

[英]How to persist an EnumMap in Hibernate/JPA?

I'm currently trying to persist data which I'd stored as a Map in Java.我目前正在尝试将我存储为Map中的 Map 的数据持久化。 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.我已经使用List让它工作了,但是当我尝试使它成为Map而不是使用@MapKeyEnumerated@MapKey时,它的行为有点出乎意料。

ExampleData.java ExampleData.java

@MapKey(name = "feature")
@MapKeyEnumerated(EnumType.STRING)
@OneToMany(targetEntity = ExampleFeature.class, mappedBy = "exampleData")
private Map<Feature, ExampleFeature> features;

ExampleFeature.java 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当从应用程序中持久化实体时, ExampleFeature确实出现在Map中,但实例中的所有属性都是默认的 Java 值,并且在退出之后

Dependencies依赖项

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.问题是在项目中, #save()仅在ExampleData上被调用,而不是在其下的任何关系属性上。 This means that Hibernate would try to persist the ExampleData instance, however not any nested properties such as the EnumMap .这意味着 Hibernate 将尝试保留ExampleData实例,但不会保留任何嵌套属性,例如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 .解决方案是设置cascade = CascadeType.ALL ,这将告诉 Hibernate 在保持ExampleData时保持关系实体中的更改,例如ExampleFeature

ExampleData.java ExampleData.java

@MapKey(name = "feature")
@MapKeyEnumerated(EnumType.STRING)
@OneToMany(targetEntity = ExampleFeature.class, mappedBy = "exampleData", cascade = CascadeType.ALL)
private Map<Feature, ExampleFeature> features;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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