短いバージョンは次のとおりです。Spring Data Rest PATCH メソッドを使用して、Postgres フィールドに含まれる JSON オブジェクトにパッチを適用する方法は?jsonb
ここに長いバージョンがあります。次のエンティティを検討してください。
@Entity
@Table(name = "examples")
public class Example {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String jsonobject;
@JsonRawValue
public String getJsonobject() {
return jsonobject == null ? null : jsonobject;
}
public void setJsonobject(JsonNode jsonobject) {
this.jsonobject = jsonobject == null ? null : jsonobject.toString();
}
}
jsonobject
Postgres タイプjsonb
です。これらのゲッター/セッターは、ここで言及されている Spring Data Rest のためにシリアル化/逆シリアル化する方法です。また、これらの回答に記載されているように、フィールドに独自のタイプを与えようとしました。
私たちの目標は、Spring Data Rest を使用して、このフィールドに含まれる JSON オブジェクトにパッチを適用することです。
例えば:
GET /examples/1
{
"id": 1,
"jsonobject": {
"foo": {"bar": "Hello"},
"baz": 2
}
}
PATCH /examples/1
{
"jsonobject": {
"foo": {"bar": "Welcome"}
}
}
期待される出力:
GET /examples/1
{
"id": 1,
"jsonobject": {
"foo": {"bar": "Welcome"},
"baz": 2
}
}
現在の出力:
GET /examples/1
{
"id": 1,
"jsonobject": {
"foo": {"bar": "Welcome"}
}
}
Spring Data Rest は、リクエストされたネストされたプロパティにのみパッチを適用するために JSON オブジェクトのプロパティを掘り下げようとするのではなく、Example リソースにパッチを適用し、リクエストされた各属性の値をオーバーライドします。
これは、Spring Data Rest のapplication/merge-patch+json
およびapplication/json-patch+json
メディア タイプのサポートが役立つと考えたときです。各メディア タイプの出力は次のとおりです。
application/merge-patch+json
:
PATCH /examples/1
{
"jsonobject": {
"foo": {"bar": "Welcome"}
}
}
出力:
GET /examples/1
{
"id": 1,
"jsonobject": {
"foo": {"bar": "Welcome"}
}
}
application/json-patch+json
:
PATCH /examples/1
[
{ "op": "replace", "path": "/jsonobject/foo/bar", "value": "Welcome" }
]
出力:
{
"cause": {
"cause": null,
"message": "EL1008E:(pos 8): Property or field 'foo' cannot be found on object of type 'java.lang.String' - maybe not public?"
},
"message": "Could not read an object of type class com.example.Example from the request!; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 8): Property or field 'foo' cannot be found on object of type 'java.lang.String' - maybe not public?"
}
これは同じ考えに帰着します。エンティティ属性のみが検索され、完全にオーバーライドされるか、見つからないかのいずれかです。
問題は次のとおりです。Spring Data Rest がjsonb
フィールドを処理していることを認識し、エンティティ属性を検索するだけでなく、JSON のネストされたプロパティを検索する方法はありますか?
注意:@Embeddable/@Embedded
注釈は、ネストされたプロパティ名を知っていることを意味するため、回避される可能性が最も高く、jsonb
フィールドへの関心が低下します。
読んでくれてありがとう。