问题
I am very new to JPA/Hibernate. In my app, I am using Spring Data JPA. I have a requirement to store MultivalueMap in Mysql DB. I have found examples only based on Map, but not MultiValueMap.
At first, is that possible to store MultiValueMap in MySQL DB?
Second, I will be glad, if someone show me some good example on above.
回答1:
You can store Map<K, List<V>>
as Set<Map.Entry<K, List<V>>>
this way.
@Entity
public class Entity {
//...
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "entity_id")
private Set<MultiValueMapEntry> multiValueMap = new ArrayList<>();
}
@Entity
public class MultiValueMapEntry {
private String key;
@ElementCollection
private List<String> values = new ArrayList<String>();
}
In Entity class use @OneToMany Unidirectional relation for every Map.Entry<K, List<V>>
and use @ElementCollection
for List<V>
of every map entry.
To learn about @OneToMany Unidirectional see here and to learn about @ElementCollection see here
And for Set<Map.Entry<K, List<V>>>
to Map<K, List<V>>
converstion see here
来源:https://stackoverflow.com/questions/61561728/how-to-store-multivaluemap-in-mysql-using-jpa-hibernate