JPA多对多映射更新问题

问题描述

更新记录时我遇到了“多对多”映射问题

我有两个名为Pack和Channels的表,Pack可能有很多通道,并且通道可以分配给很多包。当我创建数据包时,我会附加该频道,并且该频道可以正常工作,但是当我更新一个数据包中的频道时,所有其他数据包也会影响删除的分配频道。

添加2个ID为3,7的包装后,这里是多对多表

enter image description here

然后在更新包ID 3之后

enter image description here

更新一个包,然后将删除所有其他与包相关的频道

Pack Class

@ManyToMany(cascade = {CascadeType.MERGE})
@JoinTable(name = "PacksChannels",joinColumns = @JoinColumn(name = "pack_id",referencedColumnName = "packId"),inverseJoinColumns = @JoinColumn(name = "channel_id",referencedColumnName = "channelId"),uniqueConstraints = {@UniqueConstraint(columnNames = {"pack_id","channel_id"})})
List<Channel> channels;

频道类别

@ManyToMany(cascade = {CascadeType.MERGE})
@JoinTable(name = "PacksChannels",joinColumns =  @JoinColumn(name = "channel_id",inverseJoinColumns = @JoinColumn(name = "pack_id","channel_id"})})
@JsonIgnore
List<Pack> packs;

创建包

@Override
public Pack save(Pack pack) {



        Pack savePack = packRepository.save(pack);
        return savePack;
    }

在服务层上更新包

@Override
    public Pack update(Pack pack,String ref) {

      
            //I've method call find pack by ref and I get the pack according to ref user pass and then update the pack.

            Pack newPack = packRepository.findPackByRef(ref).get();
            newPack.setPackName(pack.getPackName());
            newPack.setChannels(pack.getChannels());
            Pack savedPack = packRepository.save(newPack);

            return savedPack;
        }

添加频道的方式

enter image description here

示例包Json传递到更新包方法

{
    "packId": 3,"packName": "Test1","ref": "1604905979484.55","channels": [
        {
            "channelId": 1,"name": "test"
        },{
            "channelId": 2,"name": "hShenid"
        },{
            "channelId": 3,"name": "Genesis"
        }
    ]
    
}

解决方法

删除层叠选项后,问题已解决

@ManyToMany()
    @JoinTable(name = "PacksChannels",joinColumns = @JoinColumn(name = "pack_id",referencedColumnName = "packId"),inverseJoinColumns = @JoinColumn(name = "channel_id",referencedColumnName = "channelId"),uniqueConstraints = {@UniqueConstraint(columnNames = {"pack_id","channel_id"})})
    List<Channel> channels;


@ManyToMany()
@JoinTable(name = "PacksChannels",joinColumns =  @JoinColumn(name = "channel_id",inverseJoinColumns = @JoinColumn(name = "pack_id","channel_id"})})
@JsonIgnore
List<Pack> packs;