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);
相关推荐
小林学习编程17 分钟前
Springboot + vue + uni-app小程序web端全套家具商场
前端·vue.js·spring boot
ladymorgana44 分钟前
【Spring boot】tomcat Jetty Undertow对比,以及应用场景
spring boot·tomcat·jetty
IT_10241 小时前
Spring Boot项目开发实战销售管理系统——系统设计!
大数据·spring boot·后端
DCTANT2 小时前
【原创】国产化适配-全量迁移MySQL数据到OpenGauss数据库
java·数据库·spring boot·mysql·opengauss
ai小鬼头2 小时前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
Touper.2 小时前
SpringBoot -- 自动配置原理
java·spring boot·后端
一只叫煤球的猫2 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
一只鹿鹿鹿2 小时前
信息化项目验收,软件工程评审和检查表单
大数据·人工智能·后端·智慧城市·软件工程
专注VB编程开发20年3 小时前
开机自动后台运行,在Windows服务中托管ASP.NET Core
windows·后端·asp.net
程序员岳焱3 小时前
Java 与 MySQL 性能优化:MySQL全文检索查询优化实践
后端·mysql·性能优化