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);
相关推荐
薛定谔的悦10 小时前
MQTT通信协议业务层实现的完整开发流程
java·后端·mqtt·struts
enjoy嚣士10 小时前
springboot之Exel工具类
java·spring boot·后端·easyexcel·excel工具类
无限大611 小时前
职场逻辑03:3步搞定高效汇报,让领导看到你的价值
后端
盐水冰11 小时前
【烘焙坊项目】后端搭建(12) - 订单状态定时处理,来单提醒和顾客催单
java·后端·学习
紫丁香12 小时前
AutoGen详解一
后端·python·flask
小涛不学习12 小时前
Spring Boot 详解(从入门到原理)
java·spring boot·后端
Victor35613 小时前
MongoDB(51)什么是分片?
后端
Victor35613 小时前
MongoDB(50)副本集中的角色有哪些?
后端
daidaidaiyu13 小时前
Spring IOC 源码学习 声明式事务的入口点
java·spring
IT_陈寒14 小时前
JavaScript开发者必看:5个让你的代码性能翻倍的隐藏技巧
前端·人工智能·后端