2016-09-01 73 views
3

如果street爲空,可以做些什麼?我將在HTTP POST中發現異常。 NOTNULL被檢查,如果屬性爲null或不...Spring JPA @NotNull和@JsonIgnore

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

在這種情況下JsonIgnore是行不通的。爲什麼?我想,如果我用JsonIgnore NOT NULL不會被檢查....

我可以重載@NotNull@JsonIgnore或其他一些註解?

+0

你能指定好? – Vitorlui

+0

你可以多描述一下嗎? –

+1

基本上,您不應該將實體返回到http POST響應。如果它是空的,hibernate會拋出一個你應該優雅處理的異常,然後在DTO中將該屬性設置爲null將簡單地從響應中移除該標記。希望這可以幫助。 – MDaniyal

回答

1

如果你想 「忽略」 您可以使用空值:

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

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

爲什麼JsonIgnore與NOTNULL不工作?

基本上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/