1

I've a Java REST API with JPA. Whenever I create an entity, I also want to create another entity with a forgein key. Or maybe someone can advise me otherwise, I would really appreciate it and learn from it =) When i successfully create a company it will make a file entity in the database as well, so that works fine. but, Whenever I execute a findAll method in the JPA repository it will give me a loop of the one company that i've created. like this:

findAll()

If you need any more information, please let me know!

Company.class

package nl.hulpvriend.dehulpvriend.company;
import javax.validation.constraints.NotNull;
import lombok.*;
import nl.hulpvriend.dehulpvriend.file.File;

import javax.persistence.*;
import javax.validation.constraints.Size;

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
public class Company {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @NotNull
    private String email;

    @Column(unique = true)
    @NotNull(message = "The company name cannot be empty")
    @Size(max = 30, message = "Company name cannot be longer than 30 characters")
    private String name;

    @NotNull(message = "Company must contain a service type")
    @Enumerated(EnumType.STRING)
    private ServiceType serviceType;

    private double stars;

    private Integer pricePerHour;

    private String description;

    private String kvk;

    @OneToOne(mappedBy="company", cascade = CascadeType.ALL)
    private File file;


}

File.class

package nl.hulpvriend.dehulpvriend.file;

import lombok.*;
import nl.hulpvriend.dehulpvriend.company.Company;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import javax.validation.constraints.NotNull;

@AllArgsConstructor
@Getter
@Setter
@NoArgsConstructor
@Entity
@Data
public class File {

    @Id
    private Integer id;

    private String fileId;

    @OneToOne(fetch = FetchType.EAGER)
    @MapsId
    private Company company;

    @NotNull(message = "Must contain a data")
    @Lob
    private byte[] data;

    private String downloadUrl;

    private String fileName;

    private String fileType;

    public File(String fileName, String fileType, byte[] data) {
        this.fileName = fileName;
        this.fileType = fileType;
        this.data = data;
    }

}
Bart
  • 195
  • 2
  • 14
  • Possible duplicate of [how to Fix spring boot one to many bidirectional infinity loop?](https://stackoverflow.com/questions/49130173/how-to-fix-spring-boot-one-to-many-bidirectional-infinity-loop) – Dherik Jun 13 '19 at 20:16

1 Answers1

1

Add JsonIgnore to one of the references to break the loop:

For example in the File class:

@JsonIgnore
@OneToOne(fetch = FetchType.EAGER)
@MapsId
private Company company;
Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82