我有一个 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
没有保留在数据库中。我没有任何 setter 。
有什么办法可以实现这一点吗?
更新
公认的解决方案是“侵入性较小”的解决方案。贾罗德·罗伯森 (Jarrod Roberson) 提出的方案也完美无缺。最终,您可以通过在 col2
上使用 setter 并在那里设置 col3
的值来实现相同的目的 - 但我不喜欢这个......尽管这是个人偏好。
最佳答案
虽然有一个可接受的答案,但它似乎过于复杂,并且需要删除违反 JPA 规范的默认构造函数。
第 2.1 节
The entity class must have a no-arg constructor. The entity class may have other constructors as well. The no-arg constructor must be public or protected.
没有必要让 jackson 参与其中。您可以简单地使用 JPA 预持久监听器来确保在刷新操作之前设置 col3
https://docs.jboss.org/hibernate/orm/4.0/hem/en-US/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;
}
}
关于java - 在 Spring Boot 应用程序上保留 JPA(加上 Jackson)中的 "computed"字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46106555/