I have en entity class which has an natural ID field mapped as @Id
and I don't have any surrogate ID(invented field only for table ID) field. And, in the Jackson marshalled JSON I see an extra id
exposed.
So instead of:
{
"bin":"123456", ...
}
I see:
{
"id":"123456", "bin":"123456", ...
}
which I don't want because they are repeated information. How can I prevent this?
I haven't touched REST/MVC configuration adapter; they are for exposing the ID classes, but I don't want that.
Bean:
@Entity
@Data
@Table(name="bin_info")
public class BinInfo implements Serializable, Persistable<String> {
@Id
@NotBlank //this is for absent parameter. Not equal to Pattern regex check
@Pattern(regexp = "^\\d{6,8}$") //6-8 digits
@Column(name="bin")
@JsonProperty("bin")
private String bin;
...
I am with these dependencies:
dependencies {
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.boot:spring-boot-starter-aop')
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-data-rest')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-undertow')
runtime('com.h2database:h2')
runtime('org.postgresql:postgresql')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('io.cucumber:cucumber-java:3.0.2')
testCompile('io.cucumber:cucumber-junit:3.0.2')
testCompile('io.cucumber:cucumber-spring:3.0.2')
}
Spring Boot 2.0.3.
Thanks all, I think it has to do with some configuration of Spring or Jackson that will automatically expose the field mapped with @Id
. I can just guess because no time for a confirmation.
And some colleague suggests me to define a DTO instead of putting the @Jsonxxx
annotations in the class, saying the model represents data model and are related to the table, while DTO is related with view layer. So I did it and now all is fine.
Now the model is free of id
field and @JsonProperty
/@JsonIgnore
:
@Entity
@Data
@Table(name="bin_info")
public class BinInfo implements Serializable, Persistable<String> {
@Id
@NaturalId
@NotBlank //this is for absent parameter. Not equal to Pattern regex check
@Pattern(regexp = "^\\d{6,8}$") //6-8 digits
@Column(name="bin")
//@JsonProperty("bin")
private String bin;
...
And the DTO is totally without @Id
:
@Data
public class BinInfoDTO {
@JsonProperty("bin")
private String bin;
@JsonProperty("json_full")
private String json_full;
...
When I retrieve an entity, with a mapping method I set all values I need in a DTO to the DTO and return it to the endpoint. Then the JSON is normal and fine.