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

如何解决具有@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`

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-