German Avalos
German Avalos

Reputation: 73

JPA ManyToOne/OneToMany bidirectional get duplicate data

I am building a REST API with Spring 2.1 and I am getting duplicate data to consult the ManyToOne relationship.

Localidad:

@Entity
@Table(name = "localidad")
public class Localidad implements Serializable {

    private static final long serialVersionUID = -7258462202419598287L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idLocalidad;

    private String nombreLocalidad;

    private BigDecimal precioEnvio;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "provinciaIdProvincia")
    private Provincia provincia;

    public Localidad() {}

    public Localidad(String nombreLocalidad, BigDecimal precioEnvio) {
        this.nombreLocalidad = nombreLocalidad;
        this.precioEnvio = precioEnvio;
    }
...

Provincia:

@Entity
@Table(name = "provincia")
public class Provincia implements Serializable {

    private static final long serialVersionUID = 3324427184301992595L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idProvincia;

    private String nombreProvincia;

    @OneToMany(mappedBy= "provincia", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<Localidad> localidades = new HashSet<Localidad>();

    public Provincia() {}

    public Provincia(String nombreProvincia) {
        this.nombreProvincia = nombreProvincia;
    }
...

I access information by implementing CrudRepository and Service @Autowired

Duplicate data HTTP GET Request:

Duplicate Data

Thanks

Upvotes: 0

Views: 1131

Answers (1)

Omoro
Omoro

Reputation: 972

The problem is caused by Jackson doing cyclic serialization on the provincia and the localidades fields. This can be solved by using the @JsonIgnoreProperties annotation. so in the Localidad class or entity add the annotation as follows:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "provinciaIdProvincia")
@JsonIgnoreProperties("localidades")
private Provincia provincia;

And in the Provincia class modifiy the Set<Localidad>(btw you can just use a List<Localidad> instead) like this:

@OneToMany(mappedBy= "provincia", cascade = CascadeType.ALL, fetch = 
FetchType.LAZY)
@JsonIgnoreProperties("provincia")
private Set<Localidad> localidades = new HashSet<Localidad>();

With this changes your Rest API should now show no duplicates. You have to ignore the fields that define the association between the two classes or entities. In case you have used @JsonProperty to define the fields names, use the names used in the @JsonProperty definition for @JsonIgnoreProperties.

Upvotes: 1

Related Questions