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 分钟前
1.springmvc基础入门(一)
spring·springmvc
MacroZheng34 分钟前
IDEA官方中文文档正式发布,太全了!
java·后端·intellij idea
fashia40 分钟前
Java转Go日记(五十七):gin 中间件
开发语言·后端·golang·go·gin
ak啊42 分钟前
深入浅出:计算机网络中的数据封装与解封装之旅
前端·后端
写bug写bug1 小时前
深入理解MySQL binlog
数据库·后端·mysql
噼里啪啦啦.1 小时前
RabbitMQ在SpringBoot中的应用
spring boot·rabbitmq·java-rabbitmq
这里有鱼汤1 小时前
AKShare被限IP、Tushare要积分?这才是最适合量化用的数据接口
后端·python
天天摸鱼的java工程师2 小时前
凌晨四点,掘金签到 bug 现场抓包,开发同学速来认领!
服务器·前端·后端
SimonKing2 小时前
揭秘自定义注解,背后的面向切面编程(AOP)的艺术
java·后端·架构
赤橙红的黄2 小时前
Spring BeanPostProcessor
java·spring