Win32
Win32

Reputation: 159

JPA: mapping a java.util.Map to a single table

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?

Upvotes: 0

Views: 1104

Answers (2)

Christian Beikov
Christian Beikov

Reputation: 16400

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))
    }
}

Upvotes: 1

Thomas
Thomas

Reputation: 471

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.

Upvotes: 0

Related Questions