How to Store MultivalueMap in MySQL using JPA/Hibernate

∥☆過路亽.° 提交于 2020-05-28 09:22:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!