You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot关联实体查询报错:仅createOwner可用,查询方法抛异常

问题排查请求

本人是Spring Boot新手,当前项目中仅createOwner()方法可正常工作,调用findById()或findAll()方法从关联实体获取数据时会抛出大量异常。

已通过Postman成功提交以下JSON数据保存Owner实体:

{        
    "ownerName": "Harry",
    "car":{
        "car_id" : "2"
    }
}

相关代码及数据库信息

Owner实体类

@Entity
@Data
public class Owner {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long owner_id;

    private String ownerName;

    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "c_id", referencedColumnName = "car_id" )
    private Car car;
}

Car实体类

@Entity
@Data
public class Car {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long car_id;
    private String car_name;

    @OneToOne(mappedBy = "car")
    private Owner owner;
}

控制器代码

@RestController
public class OwnerController {

    @Autowired
    private OwnerRepository ownerRepo;

    @PostMapping("/createowner")
    public Owner createOwner(@RequestBody Owner owner){
        return ownerRepo.save(owner);
    }

    @GetMapping("/findownerbyid")
    public Owner getByID(){
        return ownerRepo.findById(2L).get();
    }

    @GetMapping("/carlist")
    public List<Owner> getOwnerList(){
        return ownerRepo.findAll();
    }
}

Owner仓库

@Repository
public interface OwnerRepository extends JpaRepository<Owner, Long> {
}

Car仓库

@Repository
public interface CarRepo extends JpaRepository<Car , Long> {
}

数据库数据

Owner表数据

+----------+------------+------+
| owner_id | owner_name | c_id |
+----------+------------+------+
|        1 | Tom        |    1 |
|        2 | Harry      |    2 |
+----------+------------+------+

Car表数据

+--------+----------+
| car_id | car_name |
+--------+----------+
|      1 | Toyota   |
|      2 | Audi     |
+--------+----------+

报错情况

调用getOwnerList()时出现无限递归导致的JSON序列化异常,核心表现为Jackson无法处理双向关联的循环引用:Owner对象包含Car,Car对象又包含Owner,序列化时反复嵌套解析,最终触发栈溢出错误。


内容的提问来源于stack exchange,提问作者Shadow Face

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 22:57:19