1

I have a user entity with a list of settings. Originally I used List but using Map returns a JSON that is easier to search.

List version:

Database column declaration in entity:

private List<Setting> settings = new ArrayList<>();

Rendered JSON on GET:

"settings": [
    {"name1" : "setting 1", "value" : 5},
    {"name2" : "setting 2", "value" : 6},
]

JSON-patch:

[{"op":"replace","path":"/settings/0/value", "value": "6"}]

Map version:

Database column declaration in entity:

@MapKey(name = "name")
private Map<String, Setting> settings = new HashMap<>();

Rendered JSON on GET:

"settings": {
    "name1": {"name1" : "setting 1", "value" : 5},
    "name2": {"name2" : "setting 2", "value" : 6},
}

How to patch this? Tried this, but it is not working. Jackson wants a property named name1 in my POJO.

[{"op":"replace","path":"/settings/name1/value", "value": "6"}]
2
  • What are you trying to do? Do you want to add/remove a new setting from the list? Is Setting another entity with its own repository? Commented May 4, 2018 at 6:20
  • I want to change the value for the setting with the map key 'name1', IOW I want to address an element in a Map by its key instead of addressing it by index in a List. Yes, Setting is another entity, but it does not have a repository. Commented May 6, 2018 at 13:36

1 Answer 1

2

Since you prefer having settings field as Map, here is one way you could implement it:

@ElementCollection(fetch = FetchType.EAGER)
@MapKeyColumn(name = "settings_name")
@Column(name = "settings_value")
@CollectionTable(name = "entity_settings", joinColumns = @JoinColumn(name = "entity"))
private final Map<String, String> settings = new HashMap<>();

Now to add or replace a setting, all you need to do is a PATCH call on the entity endpoint PATCH /entity/id with a JSON object in request body:

Content-Type: application/json
PATCH /entity/id
{
  "settings": {
     "name1": "5"
  }
}

Above request would create a new setting with key name and value 5 if it doesn't exist already else replace the value.

I would argue Setting need not be an entity and can be completely owned by the containing entity. Unless you want Setting to be accessible on its own but as you said in comments it doesn't have its own repository, I assume that's not the case.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.