API 使用@OneToMany 关系抛出 StackOverflow 错误

API throwing StackOverflow Error with a @OneToMany Relationship

我对我的 MYSQL 数据库做了一些更改,这样一个产品可以有多个与之关联的图像(一对多),但是自从进行此更改后,我看到一些奇怪的行为并且程序抛出一个Whosebug Exception。好像程序在崩溃和抛出错误之前陷入了一个连续的循环。

我的模型 classes 的结构如下:

@Entity
@Table(name="products")
public class Products {
    
    public Products(String name, String price, String added_on, String category_id, String image_name, String description, List<ImageModel> imageModel) {
        super();
        this.name = name;
        this.price = price;
        this.added_on = added_on;
        this.category_id = category_id;
        this.image_name = image_name;
        this.description = description;
        this.imageModel = imageModel;
    }
    
    public Products(String name, String price, String added_on, String category_id, String description) {
        super();
        this.name = name;
        this.price = price;
        this.added_on = added_on;
        this.category_id = category_id;
        this.description = description;
    }
    
    public Products() {}
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String name;
    private String price;
    private String added_on;
    private String category_id;
    private String image_name;
    private String description;
    private String image_id;
    
    @ManyToOne(optional=false)
    @JoinColumn(name = "category_id", insertable=false, updatable=false)
    private Category category;
    
    @OneToMany(mappedBy = "product")
    private List<ImageModel> imageModel;

    // Getters & Setters

此 class 然后链接到 ModelImage 如下:

@Entity
@Table(name = "image_table")
public class ImageModel {

public ImageModel() {
    super();
}

public ImageModel(String name, String type, byte[] picByte, Products product) {
    this.name = name;
    this.type = type;
    this.picByte = picByte;
    this.product = product;
}

public ImageModel(String name, String type, byte[] picByte) {
    this.name = name;
    this.type = type;
    this.picByte = picByte;
}


@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "name")
private String name;

@Column(name = "type")
private String type;

// image bytes can have large lengths so we specify a value
// which is more than the default length for picByte column
@Column(name = "picByte", length = 10000)
private byte[] picByte;

@ManyToOne
@JoinColumn(name="product_id")
private Products product;

// Getters Setters

当我添加产品时,执行以下代码并且似乎按预期添加了所有内容:

@PostMapping(value = "imageUploadMultiple")
public ResponseEntity<ImageResponse> addProductAndImages(@RequestParam("imageFiles") MultipartFile[] files, @RequestParam("productName") String productName, @RequestParam("productDescription") String productDescription, @RequestParam("productPrice") String productPrice, @RequestParam("categoryId") String categoryId) throws IOException {      
    // Need to save product first then get the id and save all images with the productId
    
    Products products = productService.addProduct(productName,  productDescription,  productPrice,  categoryId);

    
    Arrays.asList(files).stream().forEach(file -> {
        ImageModel img = null;
        try {
            img = new ImageModel(file.getOriginalFilename(), file.getContentType(), compressBytes(file.getBytes()), products);
            imageRepository.save(img);
        } catch (IOException e) {
            e.printStackTrace();
        }           
    });
    

    return ResponseEntity.ok().build();
}

此端点接受多个图像和与图像对应的表单数据(产品详细信息等)

但是,当我调用端点以获取基于特定 categoryId 的所有产品时出现问题:

    @RequestMapping(value = "getProductsByCategory", produces = MediaType.APPLICATION_JSON_VALUE)
public List<Products> getProductsByCategory(@RequestBody HashMap<String, String> request) {
    String category_id = request.get("cat_id");
    List<Products> list = productService.getProductsByCategory(category_id);
    return list;
}

然后调用服务 class,然后调用存储库代码:

    @Query("Select pro FROM Products pro WHERE pro.category_id=:cat_id")
List<Products> getByCategoryId(@Param("cat_id")String cat_id);

当我 运行 处于调试模式的应用程序时,我得到以下数据(此时该特定类别 ID 只有一个产品):

注意 'ImageModel' 是 PersistentBag 类型。当我深入研究时,我将映射图像获取到特定产品。在本例中,产品有 4 张产品图片。当我深入挖掘时,我注意到只有一个连续的循环:

错误如下

java.lang.WhosebugError: null
at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_251]
at java.lang.ClassLoader.defineClass(ClassLoader.java:756) ~[na:1.8.0_251]
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.8.0_251]
at java.net.URLClassLoader.defineClass(URLClassLoader.java:468) ~[na:1.8.0_251]
at java.net.URLClassLoader.access0(URLClassLoader.java:74) ~[na:1.8.0_251]
at java.net.URLClassLoader.run(URLClassLoader.java:369) ~[na:1.8.0_251]

Could not write JSON: Infinite recursion (WhosebugError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (WhosebugError) (through reference chain: com.youtube.ecommerce.model.Products["imageModel"]->org.hibernate.collection.internal.PersistentBag[0]->com.youtube.ecommerce.model.ImageModel["product"]->com.youtube.ecommerce.model.Products["imageModel"]->org.hibernate.collection.internal.PersistentBag[0]->com.youtube.ecommerce.model.ImageModel["product"]->com.youtube.ecommerce.model.Products["imageModel"]->org.hibernate.collection.internal.PersistentBag[0]->com.youtube.ecommerce.model.ImageModel["product"]->com.youtube.ecommerce.model.Products["imageModel"]->org.hibernate.collection.internal.PersistentBag[0]->com.youtube.ecommerce.model.ImageModel["product"]->com.youtube.ecommerce.model.Products["imageModel"]->org.hibernate.collection.internal.PersistentBag[0]

错误一直在发生,所以我没有 post 完整的事情,但它不断地一遍又一遍地说同样的话。

我真的很难理解这里出了什么问题!!

这是因为当你序列化你的实体时,你会得到像

这样的图表

Product->Image[]->Product->Image[]->Product-> and so on

所以你必须在某处削减递归,例如使用 @JsonIgnore 或使用 @JsonManagedReference, @JsonBackReference`

这与您窥视实体的其中一张图像上的描述完全一致。