0

So im implmenting an API using springboot, spring-data and Jackson, but im having some troubles when im trying to POST a request to an endpoint who have a Bidirection relationship of @OneToMany.

I dont have so much background so i need really help.

I have two Entities:

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;
    }

}

and 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;
    }

}

This is my 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);
    }

}

When i POST to the URL, i get the following return

{
    "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/"
}

I Already have a Partida inside my database, but i cannot POST to this method, need really help.

6
  • please define default constructor public Partida (){}
    – Onic Team
    Mar 28, 2019 at 4:54
  • For deserialisation purposes Partida class must have a zero-arg constructor.
    – Onic Team
    Mar 28, 2019 at 4:57
  • Show the json body you're trying to send to this endpoint
    – k9yosh
    Mar 28, 2019 at 4:58
  • { "pontoA" : 1, "pontoB" : 1, "setFinalizado" : "false", "partida_id" : 1 } Json Body of my request Mar 28, 2019 at 5:08
  • @LucasDuarte try This { "partida_id": 1, "pontoA": 1, "pontoB": 1, "setFinalizado": "false" }
    – Onic Team
    Mar 28, 2019 at 5:24

2 Answers 2

0

This issue has nothing to do with JPA bi-directional mapping. Its raising error at the time of de serializing.
Partida -> should have zero argument constructor

Request payload should have { "partida":{"id":123}} in order to populate partida object property.

3
  • When i tried this, i got the follow 2019-03-28 02:48:17.679 ERROR 8180 --- [nio-5888-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause Mar 28, 2019 at 5:49
  • You were right, just the way who i pass the JSON, and the null pointer exeception was because i forgot the @Autowired annotation tho inject the dependencie. Mar 28, 2019 at 5:56
  • Thats good news at least json error is gone. private SetService setServ; is null and any operation in the object will throw null pointer exception. Mar 28, 2019 at 5:57
0

for details check this link Jackson library.

@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;
    }

}

if issue not not resolved then try JSON creator

@JsonCreator
    public Partida(@JsonProperty("id") Long id, @JsonProperty("timeA") String 
    timeA, @JsonProperty("timeB") String timeB, @JsonProperty("desc") boolean
    visitante) {
    this.id = id;
    this.timeA = timeA;
    this.timeB= timeB;
    this.visitante= visitante;
} 
2
  • It does not work eaither, i tried with the empty constructor and with the annotatio @JsonCreator, the serveris always the same error Mar 28, 2019 at 5:15
  • @LucasDuarte: create an empty constructor in your set class public Set(){} and after that share your error message
    – Onic Team
    Mar 28, 2019 at 5:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.