0

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.

john
  • 925
  • 1
  • 12
  • 20

1 Answers1

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

Eklavya
  • 17,618
  • 4
  • 28
  • 57