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);
相关推荐
不能放弃治疗1 分钟前
MCP
后端
万亿少女的梦16820 分钟前
基于Spring Boot的游戏交易管理系统设计与实现
java·spring boot·mysql·系统设计·交易管理
江湖十年1 小时前
Go 语言中 YAML to JSON 踩坑笔记
后端·go·json
你驴我2 小时前
WhatsApp 消息撤回与编辑的幂等性设计实践
java·服务器·前端·后端·python
一缕清烟在人间2 小时前
HarmonyOS开发实战:小分享-TextEditPage文字编辑器——Header+TextArea+工具栏
后端·华为·harmonyos·鸿蒙
人间凡尔赛2 小时前
K8s 十年之变:从 Cloud Native 到 AI Native,2026 年后端架构的范式革命
后端·云原生·架构
程序员cxuan2 小时前
Opus 5 深夜炸场,价格还挺香。。。
人工智能·后端·程序员
北冥you鱼2 小时前
Go 语言新手扫盲:指针 * 和 & 使用场景详解
开发语言·后端·golang
青山木2 小时前
Hot 100 ---腐烂的橘子
java·数据结构·后端·算法·leetcode·广度优先
卷无止境3 小时前
Python的collections模块:那些被低估的"瑞士军刀"
后端·python