具有@OneToMany关系的API引发StackOverflow错误

问题描述

我对MYSQL数据库进行了一些更改,以便一个产品可以具有多个与之关联的图像(一对多),但是自从进行此更改以来,我看到了一些奇怪的行为,程序抛出了StackOverflow Exception 。似乎程序在崩溃并引发错误之前被卡在连续循环中。

我的模型类的结构如下:

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

然后将该类链接到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,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;
}

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

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

当我在调试模式下运行该应用程序时,我会收到以下数据(目前,该特定categoryID只有一种产品):

Debug Window Showing contents of list

注意'ImageModel'是PersistentBag类型的。当我对此进行更深入的研究时,便获得了映射到特定产品的图像。在这种情况下,该产品有4个产品图片。当我深入研究时,我发现只有一个连续的循环:

Continuous Loop of the same data inside itself

Image Model Data

错误如下

java.lang.StackOverflowError: 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.access$100(URLClassLoader.java:74) ~[na:1.8.0_251]
at java.net.URLClassLoader$1.run(URLClassLoader.java:369) ~[na:1.8.0_251]

Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (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]

该错误不断发生,所以我没有发布完整的内容,但它不断地重复说同一件事。

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

解决方法

这是因为当您序列化您的实体时,您将拥有类似

的图形

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

因此您必须将递归削减到某个地方,例如使用@JsonIgnore或使用@JsonManagedReference,@JsonBackReference`

这正好显示在您窥视实体的一张图像上。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...