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);
相关推荐
_Aaron___5 分钟前
MyBatis 动态排序别乱用 ${}:ORDER BY 的安全写法
java·spring·mybatis
摇滚侠10 分钟前
SpringMVC 入门到实战 HttpMessageConverter 65-74
java·后端·spring·intellij-idea
Csvn26 分钟前
用户与权限管理 — 从创建到精细化管控
后端
金銀銅鐵28 分钟前
用 Tkinter 实现简单的论语第一章阅读器
后端·python
愛~杦辷个訾30 分钟前
Java Springboot使用阿里云oss对图片进行等质量压缩,转换成webp格式的压缩图。
java·spring boot·阿里云·oss
霸道流氓气质41 分钟前
Spring Boot Multipart 表单中文乱码问题全解析
java·spring boot·后端
长栎43 分钟前
Spring Boot 自动配置的3种设计模式,比 @Autowired 更值得搞懂
后端
长栎1 小时前
读 Kafka 源码才知道,你写的观察者模式就是个玩具
后端
胡萝卜术1 小时前
从零搞懂 AJAX:手把手带你从 XMLHttpRequest 到 fetch,彻底理解前后端数据交互
前端·后端·面试
RuoyiOffice1 小时前
从 0 到 1 搭建 RuoyiOffice:30 分钟跑通后端+前端+移动端
前端·spring boot·uni-app·开源·oa·ruoyioffice·hrm