I have an Entity in Spring Boot where one of its fields is an HashMap
. I saw this question but I can't use this solution, I can't have an entry for each key-value couple.
I need to have a table with a column named id
, another one named name
, etc... and at the same way a column with my Map
object. Is there a way do to this?
The only solution I came up with is to convert the map in a key-value string, and then read it back to Map, but I was wondering if there's a better and more compact way to save the map as a particular type of column data in the DB.
Asked
Active
Viewed 1,958 times
2

Usr
- 2,628
- 10
- 51
- 91
-
1A `jsonb` column? – May 06 '19 at 13:14
-
1@a_horse_with_no_name and to save data to db I simply convert HashMap to Json format and then save the json to the jsonb column? Like `myEntity.setHashMap(json)` and then `service.save(myEntity)` ? – Usr May 06 '19 at 13:18
-
1you can use hstore https://vladmihalcea.com/map-postgresql-hstore-jpa-entity-property-hibernate/ – Sharon Ben Asher May 06 '19 at 13:22
1 Answers
0
I know this is an old question, but maybe it can help someone.
As mentioned in the comments, one way is to use jsonb
PostgreSQL type, as its structure reminds of key-value pairs.
Suppose, there is a Map<String, String> map = new HashMap<>();
- Save jsonb value to PostgreSQL table
It is possible to use anObjectMapper
instance to convert Java objects into JSON strings:
ObjectMapper mapper = new ObjectMapper();
try {
String mapAsJson = mapper.writeValueAsString(map);
// then insert 'mapAsJson' to a jsonb-column
} catch (Exception ex) {
...
}
- Read jsonb value from PostgreSQL table
Again, we can use an instance ofObjectMapper
to convert jsonb column to a Java object while we are reading from the table. This code can be used directly in a repository class:
String someJsonb = "{\"A\":\"Tom\", \"B\":\"Bella\", \"C\":\"Maria\"}";
try {
Map<String, String> parsedMapData = mapper.readValue(someJsonb, Map.class);
} catch (Exception ex) {
...
}

Albina
- 1,901
- 3
- 7
- 19