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

Spring Boot一对多关联场景下用户数据更新失败问题求助

Spring Boot一对多关联场景下用户数据更新失败问题求助

大家好,我是Spring Boot的新手,现在在开发一个包含User(父实体)和Address(子实体)一对多关联的功能。目前创建用户的POST接口是正常工作的,但调用PUT接口更新用户记录时一直失败,我查了很多资料试了各种方法都没解决,想请大家帮忙看看问题出在哪里?

实体类代码

User.java

@Entity
public class User {

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

    private String name;
   // @JsonIgnore
    @JsonManagedReference
    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Address> addresses;

    // Getters and setters
}

Address.java

@Entity
public class Address {

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


    private String street;
    private String city;
    private String state;
    private String zip;

    @JsonBackReference
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    // Getters and setters
}

控制器与业务层代码

UserController.java

@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
    User existingUser = userService.getUser(id);
    existingUser.setName(user.getName());
    existingUser.setAddresses(user.getAddresses());
    return userService.updateUser(existingUser);
}

UserService.java

public User updateUser(User user) {
    return userRepository.save(user);
}

第一次报错信息

我运行后遇到了TransientObjectException异常,具体栈信息如下:

org.hibernate.TransientObjectException: persistent instance references an unsaved transient instance of 'com.clt.product_service.entity.User' (save the transient instance before flushing)
    at org.hibernate.engine.spi.CascadingActions$9.cascade(CascadingActions.java:382) ~[hibernate-core-6.6.4.Final.jar:6.6.4.Final]
    at org.hibernate.engine.spi.CascadingActions$9.cascade(CascadingActions.java:372) ~[hibernate-core-6.6.4.Final.jar:6.6.4.Final]
    at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:570) ~[hibernate-core-6.6.4.Final.jar:6.6.4.Final]
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:492) ~[hibernate-core-6.6.4.Final.jar:6.6.4.Final]

Postman返回的响应片段:

"timestamp": "2025-02-20T20:35:11.402+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "trace": "org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientObjectException: persistent instance references an unsaved transient instance of 'com.clt.product_service.entity.User' (save the transient instance before flushing)\r\n\tat org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:368)\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:246)\r\n\tat org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.

我尝试的修改及新报错

后来我按照网上的建议修改了Controller的updateUser方法:

@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
    User existingUser = userService.getUser(id);
    existingUser.setName(user.getName());
     existingUser.setAddresses(user.getAddresses().stream()
            .map(address -> {
                address.setId(null);
                address.setUser(existingUser);
                return address;
            })
            .toList());
  return userService.updateUser(existingUser);
}

现在又出现了新的错误:

"timestamp": "2025-02-21T03:47:47.749+00:00",
"status": 500,
"error": "Internal Server Error",
"trace": "java.lang.UnsupportedOperationException\r\n\tat java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)\r\n\tat java.base/java.util.ImmutableCollections$AbstractImmutableCollection.clear(ImmutableCollections.java:149)\r\n\tat org.hibernate.type.CollectionType.replaceElements(CollectionType.java:506)\r\n\tat org.hibernate.type."

真心希望大家能帮我分析下这两个错误的原因,以及我该怎么修改才能让更新功能正常工作,谢谢大家了!

备注:内容来源于stack exchange,提问作者Learner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 10:53:06