簡體   English   中英

在Spring Boot應用程序上的JPA(加上Jackson)中堅持“計算”字段

[英]Persist “computed” field in JPA (plus Jackson) on Spring Boot application

我有一個JPA實體,看起來像:

public final class Item implements Serializable {
  @Column(name = "col1")
  private String col1;

  @Column(name = "col2")
  @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
  private String col2;

  @Column(name = "col3")
  private String col3;

  Item() { }

  public Item(String col1, String col2) {
    this.col1 = col1;
    this.col2 = col2;
    col3 = col1 + col2 + "some other stuff";
  }

  // getters, equals, hashCode and toString
}

我希望能夠堅持col3 我正在通過POST發送請求,如下所示:

{
  "col1": "abc",
  "col2": "def"
}

...而我收到的是這樣的:

[
    {
        "createdAt": "2017-09-07T19:18:17.04-04:00",
        "updatedAt": "2017-09-07T19:18:17.04-04:00",
        "id": "015e5ea3-0ad0-4703-af04-c0a3d46aa836",
        "col1": "abc",
        "col3": null
    }
]

最終, col3不會col3在數據庫中。 我沒有二傳手。

有什么辦法可以做到這一點?

更新

公認的解決方案是“較少干擾”的解決方案。 Jarrod Roberson提出的建議也可以完美地工作。 最終,您可以通過在col2上使用setter並在那里設置col3的值來實現相同的目的,但是我不喜歡這個……盡管個人喜好。

之所以不能持續下去,是因為從未真正調用過您提供的帶有col1col2屬性的構造函數。 當spring從您發送到服務器的JSON中映射(借助jackson)時,它使用默認構造函數創建對象,然后調用setter(有時通過反射)來設置值。 因此, col3的數據庫中存儲的值始終為空。 請參閱Jarrod Roberson的答案如何解決它:)。

您正在尋找的是@JsonCreator它的用法如下:

@JsonCreator()
public Item(@JsonProperty("col1") String col1, @JsonProperty("col2") String col2) {
  this.col1 = col1;
  this.col2 = col2;
  this.col3 = col1 + col2 + "some other stuff";
}

然后刪除默認的no-args構造函數,Jackson將使用此構造函數,您想要的將自動進行

這是1.x時代的一項非常古老的功能 您還可以注釋static 工廠方法 ,並使構造函數private以用於需要使用更復雜的邏輯(例如使用“ 構建器模式”構造的事物)的情況。

這是一個例子:

@JsonCreator()
public static Item construct(@JsonProperty("col1") String col1, @JsonProperty("col2") String col2) {
  return new Item(col1, col2, col1 + col2 + "some other stuff");
}

private Item(final String col1, final String col2, final String col3) {
  this.col1 = col1;
  this.col2 = col2;
  this.col3 = col3;
}

盡管有一個可以接受的答案,但它似乎過於復雜,需要刪除違背JPA規范的默認構造函數。

第2.1節

實體類必須具有no-arg構造函數。 實體類也可以具有其他構造函數。 無參數構造函數必須是公共的或受保護的。

無需讓Jackson參與其中。 您可以簡單地使用JPA預持久偵聽器來確保在刷新操作之前已設置col3

https://docs.jboss.org/hibernate/orm/4.0/hem/zh-CN/html/listeners.html

public final class Item implements Serializable {
  @Column(name = "col1")
  private String col1;

  @Column(name = "col2")
  @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
  private String col2;

  @Column(name = "col3")
  private String col3;

  Item() { }

  @PrePersist
  public void updateCol3(){
      col3 = col1 + col2;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM