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);
相关推荐
大鸡腿同学5 小时前
【成长类】《只有偏执狂才能生存》读书笔记:程序员的偏执型成长地图
后端
0xDevNull5 小时前
MySQL数据冷热分离详解
后端·mysql
一定要AK5 小时前
Spring 入门核心笔记
java·笔记·spring
AI袋鼠帝5 小时前
OpenClaw(龙虾)最强开源对手!Github 40K Star了,又一个爆火的Agent..
后端
KevinCyao5 小时前
java视频短信接口怎么调用?SpringBoot集成视频短信及回调处理Demo
java·spring boot·音视频
凯尔萨厮5 小时前
创建SpringWeb项目(Spring2.0)
spring·mvc·mybatis
總鑽風6 小时前
搭建Spring Boot + ELK日志平台,实现可视化日志监控
spring boot·elk·macos
不吃香菜学java7 小时前
Redis简单应用
数据库·spring boot·tomcat·maven
新知图书7 小时前
搭建Spring Boot开发环境
java·spring boot·后端
皮皮林5517 小时前
SpringBoot 4 最被低估的新特性:Spring Data AOT
spring boot