0

So, basically, I am trying to implement a simple key-value store for global, system-wide configurations for my application, and for that, I would like to map an entire java.util.Map to a single table in the database? So, for example:

// initialization

globalConfig.put("property1", "130")
globalConfig.put("property2", "abc")
globalConfig.put("propertyXY", "0")

is mapped to:

GLOBAL_CONFIG:

| key        | value |
|------------|-------|
| property1  | 130   |
| property2  | abc   |
| propertyXY | 0     |

Is there a clean and simple way to implement this using JPA / Hibernate?

Win32
  • 149
  • 1
  • 9
  • Does this solve your problem https://stackoverflow.com/questions/4371384/can-a-jpa-query-return-results-as-a-java-map ? – Shawrup Dec 20 '20 at 15:22
  • @Shawrup hmm... no, not really – Win32 Dec 20 '20 at 15:35
  • Why not persist a `List` with `@Entity @Table(name="GLOBAL_CONFIG") public class ConfigEntry { @Column(name = "key") @Id private String key; @Column(name = "value") private String value; /* ctor, getters, setters, ... */ }`? – Turing85 Dec 20 '20 at 15:40

2 Answers2

1

You have to map it as an entity. Something like this:

@Entity
@Table(name="GLOBAL_CONFIG")
public class GlobalConfig {
    @Id
    private String key;
    private String value;
}

If you want a map, you will have to convert a List<GlobalConfig> to a Map<String, String> through e.g. stream operations which looks roughly like this:

interface GlobalConfigRepository extends Repository<GlobalConfig, String> {
    default Map<String, String> getMap() {
        return findAll().stream().collect(Collectors.toMap(GlobalConfig::getKey, GlobalConfig::getValue))
    }
}
Christian Beikov
  • 15,141
  • 2
  • 32
  • 58
0

If this map is corresponding with a table, which I think what you want to achieve, you would need to load all entries and transform it into the map yourself. I wouldn't put it at the data layer, better to provide a service for this.

If you want to store a map on a column for one entry, I think you need a JSON field like discribed here https://vladmihalcea.com/how-to-map-json-objects-using-generic-hibernate-types/ or here https://bootify.io/docs/persist-json-with-spring-data-hibernate.html.

Thomas
  • 451
  • 2
  • 5