我有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。
谢谢。
答案 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;