我有一个带有JPA的Java REST API。每当我创建一个实体时,我也想创建一个带有forgein键的另一个实体。也许有人可以建议我,否则我将不胜感激,并从中学习=) 当我成功创建公司时,它也会在数据库中创建一个文件实体,因此效果很好。但, 每当我在JPA存储库中执行findAll方法时,都会给我一个我创建的公司的循环。 像这样:
如果您需要更多信息,请告诉我!
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;
}
}
答案 0 :(得分:1)
将JsonIgnore添加到引用之一以打破循环:
例如在File类中:
@JsonIgnore
@OneToOne(fetch = FetchType.EAGER)
@MapsId
private Company company;