【问题标题】:Spring JPA @NotNull and @JsonIgnoreSpring JPA @NotNull 和 @JsonIgnore
【发布时间】:2016-09-01 13:06:29
【问题描述】:

如果 street 为空,可以做什么?我会在HTTP POST 中得到一个例外。 NotNull 正在检查属性是否为空...

@NotNull
@Column(name = "street")
@JsonIgnore
private String street;

在这种情况下,JsonIgnore 不起作用。为什么?我想,如果我使用JsonIgnore not null 将不会被检查....

我可以用@JsonIgnore 或其他注释重载@NotNull 吗?

【问题讨论】:

  • 你能指定更好吗?
  • 你能再描述一下吗?
  • 基本上,您不应该将实体返回到 http POST 响应。如果它为空,休眠将抛出一个您应该优雅处理的异常,然后在 DTO 中将该属性设置为空,只会从响应中删除该标记。希望这会有所帮助。
  • NotNull - 是 JSR-303 bean 验证注释,而 JsonIgnore 是 Jackson 注释之一。他们不知道彼此。在您的代码中,您应该在验证之前手动设置此字段的值以通过它。您的目的和理想的结果是什么(在业务层面上)?
  • 如果值为空,我想忽略该字段。有可能吗?

标签: java spring hibernate bean-validation


【解决方案1】:

如果你想“忽略”空值,你可以使用:

@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

来自: How to tell Jackson to ignore a field during serialization if its value is null?

为什么带有 NotNull 的 JsonIgnore 不起作用?

基本上JSonIgnore注解和Not Null没有关系,因为第一个是Jackson,另一个是JPA。

我相信这些话题可以帮助你:

Serializing JPA entities to JSON using Jackson

Confusion: @NotNull vs @Column(nullable = false)

http://www.davismol.net/2015/03/10/jackson-json-difference-between-jsonignore-and-jsonignoreproperties-annotations/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-31
    • 2011-11-18
    • 2013-11-22
    • 1970-01-01
    • 2010-12-27
    • 1970-01-01
    • 2019-01-07
    相关资源
    最近更新 更多