如何正确发布到双向关系

时间:2019-03-28 04:47:42

标签: java spring-boot spring-mvc jackson spring-data

因此,我使用springboot,spring-data和Jackson来实现API,但是在尝试向具有@OneToMany双向关系的端点发布请求时遇到麻烦。

我没有那么多背景,所以我需要真正的帮助。

我有两个实体:

Partida

package lucas.duarte.jazz.model.bean;

import java.io.Serializable;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonProperty;

@Entity
public class Partida implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String timeA;
    private String timeB;
    private boolean visitante;
    @OneToMany(mappedBy = "partida", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<Set> sets;


    public List<Set> getSets() {
        return sets;
    }

    public void setSets(List<Set> sets) {
        this.sets = sets;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTimeA() {
        return timeA;
    }

    // Mocado o valor pois o Time A sempre e a Sao Judas
    public void setTimeA(String timeA) {
        this.timeA = timeA;
    }

    public String getTimeB() {
        return timeB;
    }

    public void setTimeB(String timeB) {
        this.timeB = timeB;
    }

    public boolean isVisitante() {
        return visitante;
    }

    public void setVisitante(boolean visitante) {
        this.visitante = visitante;
    }

}

和SET

package lucas.duarte.jazz.model.bean;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

@Entity
@Table(name = "meu_set")
public class Set implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "ponto_a")
    private long pontoA;
    @Column(name = "ponto_b")
    private long pontoB;
    @Column(name = "set_finalizado")
    private boolean setFinalizado;
    @ManyToOne
    @JoinColumn(name = "partida_id")
    private Partida partida;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public long getPontoA() {
        return pontoA;
    }

    public void setPontoA(long pontoA) {
        this.pontoA = pontoA;
    }

    public long getPontoB() {
        return pontoB;
    }

    public void setPontoB(long pontoB) {
        this.pontoB = pontoB;
    }

    public boolean isSetFinalizado() {
        return setFinalizado;
    }

    public void setSetFinalizado(boolean setFinalizado) {
        this.setFinalizado = setFinalizado;
    }

    public Partida getPartida() {
        return partida;
    }

    public void setPartida(Partida partida) {
        this.partida = partida;
    }

}

这是我的SetControler

package lucas.duarte.jazz.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriComponentsBuilder;

import lucas.duarte.jazz.model.bean.Set;
import lucas.duarte.jazz.model.service.SetService;

@Controller
@RequestMapping("/api")
public class SetController {

    private SetService setServ;

    @RequestMapping(value = "/set/", method = RequestMethod.POST)
    public ResponseEntity<?> salvarSet(@RequestBody Set set, UriComponentsBuilder ucBuilder) {
        System.out.println("Vou cadastrar um set vinculado a uma partida");
        System.out.println(set.getPartida().getId());
        setServ.salvarSet(set);
        return new ResponseEntity(HttpStatus.CREATED);
    }

}

当我发布到URL时,我得到以下回报

{
    "timestamp": "2019-03-28T04:17:46.857+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "JSON parse error: Cannot construct instance of `lucas.duarte.jazz.model.bean.Partida` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `lucas.duarte.jazz.model.bean.Partida` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)\n at [Source: (PushbackInputStream); line: 5, column: 14] (through reference chain: lucas.duarte.jazz.model.bean.Set[\"partida\"])",
    "path": "/api/set/"
}

我的数据库中已经有一个Partida,但是我无法开机自检,需要真正的帮助。

2 个答案:

答案 0 :(得分:1)

此问题与JPA双向映射无关。反序列化时它的上升错误。
Partida->应具有零参数构造函数

请求有效载荷应具有{“ partida”:{“ id”:123}},以便填充partida对象属性。

答案 1 :(得分:0)

有关详细信息,请检查此链接Jackson库。

api_data = APIData()


results = api_data.search_list_by_keyword(
                       part='snippet',
                       maxResults=25,
                       order='date')


print(results)

resultsTwo = api_data.get_next_page()

print(resultsTwo)

如果问题没有解决,请尝试使用JSON创建器

@Entity
public class Partida implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String timeA;
    private String timeB;
    private boolean visitante;
    public  Partida(){
    //Default constructor required here 
    }
    @OneToMany(mappedBy = "partida", fetch = FetchType.LAZY, cascade = 
    CascadeType.ALL)
    private List<Set> sets;


    public List<Set> getSets() {
        return sets;
    }

    public void setSets(List<Set> sets) {
        this.sets = sets;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTimeA() {
        return timeA;
    }

    // Mocado o valor pois o Time A sempre e a Sao Judas
    public void setTimeA(String timeA) {
        this.timeA = timeA;
    }

    public String getTimeB() {
        return timeB;
    }

    public void setTimeB(String timeB) {
        this.timeB = timeB;
    }

    public boolean isVisitante() {
        return visitante;
    }

    public void setVisitante(boolean visitante) {
        this.visitante = visitante;
    }

}