Hibernate级联错误

前言

今天在使用jpa中的级联保存时,发现报

ini 复制代码
A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance;

原因分析

其原因User实体类有个字段

其关联表为

less 复制代码
@Entity
@Table(name = "sys_user_client_type")
@Data
@FieldNameConstants
public class UserClientType extends FullAuditedEntity {
    private static final long serialVersionUID= -1;

    /**
     * 客户端类型
     */
    @Enumerated(EnumType.STRING)
    private ClientTypeEnum clientType;

    /**
     * 用户
     */
    @ManyToOne(optional = false, targetEntity=User.class)
    @JoinColumn(name = "user_id", referencedColumnName = BaseEntity.Fields.id)
    private User user;

}

在使用User更新级联的时候

ini 复制代码
if (CollectionUtils.isNotEmpty(createOrUpdateUserInput.getUserClientTypes())) {
    List<UserClientType> userClientTypeList = createOrUpdateUserInput.getUserClientTypes().stream()
            .distinct()
            .map(e -> {
                UserClientType userClientType = new UserClientType();
                userClientType.setClientType(e);
                userClientType.setUser(user);
                return userClientType;
            }).collect(Collectors.toList());
    user.setClientTypes(userClientTypeList);
}

报错,也就是说,更新该字段时不能使用setClientTypes(),需要使用set类的add或者addAll方法进行更新。

ini 复制代码
// 设置clientType
List<ClientTypeEnum> clientTypeEnums = createOrUpdateUserInput.getUserClientTypes();
if (clientTypeEnums != null) {
    List<UserClientType> userClientTypes = clientTypeEnums.stream().map(t -> {
        UserClientType clientType = new UserClientType();
        clientType.setClientType(t);
        clientType.setUser(user);
        return clientType;
    }).collect(Collectors.toList());
    user.getClientTypes().clear();
    user.getClientTypes().addAll(userClientTypes);
相关推荐
用户15129054522044 分钟前
Langfuse-开源AI观测分析平台,结合dify工作流
后端
南囝coding1 小时前
Claude Code 从入门到精通:最全配置指南和工具推荐
前端·后端
会开花的二叉树1 小时前
彻底搞懂 Linux 基础 IO:从文件操作到缓冲区,打通底层逻辑
linux·服务器·c++·后端
lizhongxuan2 小时前
Spec-Kit 使用指南
后端
爱吃烤鸡翅的酸菜鱼2 小时前
【Spring】原理解析:Spring Boot 自动配置
java·spring boot
十八旬2 小时前
苍穹外卖项目实战(day7-1)-缓存菜品和缓存套餐功能-记录实战教程、问题的解决方法以及完整代码
java·数据库·spring boot·redis·缓存·spring cache
会豪2 小时前
工业仿真(simulation)--发生器,吸收器,缓冲区(2)
后端
SamDeepThinking2 小时前
使用Cursor生成【财务对账系统】前后端代码
后端·ai编程·cursor
饭碗的彼岸one2 小时前
C++ 并发编程:异步任务
c语言·开发语言·c++·后端·c·异步
会豪2 小时前
工业仿真(simulation)--仿真引擎,离散事件仿真(1)
后端