【问题标题】:API throwing StackOverflow Error with a @OneToMany RelationshipAPI 使用 @OneToMany 关系引发 StackOverflow 错误
【发布时间】:2020-09-15 14:15:35
【问题描述】:

我对我的 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 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

这个类然后链接到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;
}

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

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

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

注意“ImageModel”是一个PersistentBag 类型。当我深入研究时,我会得到特定产品的映射图像。在这种情况下,该产品有 4 个产品图片。当我更深入地挖掘时,我注意到只有一个连续的循环:

报错如下

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]

错误一直在继续,所以我没有发布完整的内容,但它不断地一遍又一遍地说同样的事情。

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

【问题讨论】:

标签: java jpa stack-overflow one-to-many


【解决方案1】:

这是因为当你序列化你的实体时,你会得到类似的图表

Product-&gt;Image[]-&gt;Product-&gt;Image[]-&gt;Product-&gt; and so on

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

这在您窥视实体的一张图像上准确描绘。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    相关资源
    最近更新 更多