微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JPA多对多映射更新问题

如何解决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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。