Spring DataRest插入如何仅传递id关系而不是实体

时间:2018-12-07 21:59:48

标签: spring spring-boot spring-data-jpa spring-data spring-rest

我有2个具有OneToOne RelationShip的实体,方法是:

Grupo.java:

@OneToOne(fetch=FetchType.LAZY)
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
@JoinColumn(name = "administradorId")
private Usuario administrador;

Usuario.java:

@OneToOne(mappedBy = "administrador",fetch=FetchType.LAZY)
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
private Grupo grupo;

通过“发帖请求”插入群组时,我想这样做:

{
"titulo":"title",
"descripcion":"cosa",
"activo":true,
"administrador":2,
"portada": ""
}

但是唯一可行的方法是

 {
    "titulo":"title",
    "descripcion":"cosa",
    "activo":true,
    "administrador": {"id":2},
    "portada": ""
    }

我不想传递整个实体{“ id”:2}只希望传递2。

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以创建自定义序列化器:

public class CustomSerializer extends JsonSerializer<User> {
      public void serialize(User value, JsonGenerator jgen,
        SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeNumber(user.getId());
     }
 } 

并且需要添加一个名为@JsonDeserialize的注释。

  @OneToOne(fetch=FetchType.LAZY)
  @JsonIdentityInfo(generator = 
  ObjectIdGenerators.PropertyGenerator.class, property = "id")
  @JsonIdentityReference(alwaysAsId = true)
  @JoinColumn(name = "administradorId")
  @JsonSerialize(using = CustomSerializer. Class) 
   private Usuario administrador;