发布到restController

时间:2019-08-16 10:06:47

标签: java spring-boot

此问题仅在此控制器上发生,因为我在模型中添加了自相关。

我阅读并搜索了其他帖子和google,并且所有解决方案都可行。

我尝试设置@JsonIdentityInfo,添加@JsonBackReference和@JsonManagedReference,此标签的顺序相反,将消耗添加到rest方法,但任何方法都有效

型号:

@Entity

@JsonIdentityInfo(
  generator = ObjectIdGenerators.PropertyGenerator.class, 
  property = "code")

@Table (name = "EP7_TRS_CODIGOS")
public class Code implements Serializable {

    private static final long serialVersionUID = 2L;

    @Id
    @Column (name = "COD_CODIGO")
    private String code;

    @Column (name = "DES_CODIGO")
    private String description;

    @Column (name = "COD_TIPO")
    private String type;

    @JsonManagedReference
    @ManyToOne
    @JoinColumn (name = "ID_ORIGEN", referencedColumnName = "ID_ORIGEN")
    private Origin origin;

    @JsonBackReference
    @ManyToOne
    @JoinColumn (name="COD_CODIGO_OBJ", referencedColumnName = "COD_CODIGO")
    private Code parent;

    @JsonManagedReference
    @OneToMany (mappedBy = "parent", fetch = FetchType.LAZY)
    private List<Code> sons;

控制器:

@PostMapping(value = "/code",
    consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
    produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<Code> saveOrUpdateCode (@RequestHeader HttpHeaders httpHeaders, @RequestBody Code code){
    logger.info(">>>> Entra en el controlador saveOrUpdateCode");
    if (httpHeaders == null || !authorized(httpHeaders)) {
        logger.error(">>>> Error de autentificacion");
        return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
    } 
    return new ResponseEntity<>(cs.save(code), HttpStatus.CREATED);
}

起源班

@Entity
// @JsonIdentityInfo(
//   generator = ObjectIdGenerators.PropertyGenerator.class, 
//   property = "id")
@Table (name = "EP7_TRS_ORIGEN")
public class Origin implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column (name = "ID_ORIGEN")
    private int id;

    @Column (name = "DES_ORIGEN")
    private String description;

    @Column (name = "COD_TIPO")
    private String type;

    @JsonBackReference
    @OneToMany (targetEntity=Code.class, mappedBy="origin", fetch = FetchType.LAZY) 
    private List<Code> codes;

1 个答案:

答案 0 :(得分:0)

发送帖子请求时,您需要添加标头Content-type和值application/json。另外,您应该从@JsonManagedReference类中删除Origin