JPA DELETE操作中的一对多关系无效

时间:2018-04-04 11:44:49

标签: java spring-boot jpa spring-data-jpa

下面给出了实体模型和存储库。

Channel.java

public class Channel extends BaseEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column(name = "channel_name")
    private String channelName;

    @Column(name = "channel_type")
    private Integer channelType;

    @Column(name = "seq_id")
    private Integer seqId;

    @Column(name = "channel_device_key")
    private String channeldeviceKey;
}

UserRoomChannel.java

public class UserRoomChannel extends BaseEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    @OneToOne
    @JoinColumn(name = "user_house_id")
    private UserHouse userHouse;

    @OneToOne
    @JoinColumn(name = "room_id")
    private Room room;

    @LazyCollection(LazyCollectionOption.FALSE)
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Channel> channels;
}

UserRoomChannelReposirtory.java

public interface UserRoomChannelRepository extends JpaRepository<UserRoomChannel, Long> {
    @Query(value = "DELETE FROM user_room_channel_channels WHERE channels_id=?1", nativeQuery = true)
    void deleteUserRoomChannelChannels(Long id);
}

我可以成功保存数据。通过此方式保存数据时,将创建名为user_room_channel_channels的第三个表。

EX:

    user_room_channel_id   channels_id
           1                   1                   
           1                   2

但是当我尝试使用channels_id删除时,它会给我错误

  

cascade =&#34; all-delete-orphan&#34;不再由拥有实体实例引用:.....

The native query what I write it execute from the command line.

但是使用JPA我无法做到。

有任何帮助或任何解决此问题的建议吗?

2 个答案:

答案 0 :(得分:2)

  

cascade =&#34; all-delete-orphan&#34;不再被引用   由拥有实体实例

是因为之前删除了你的频道(及其子节目),你会以某种方式执行以下操作:

  • 您从数据库中加载了UserRoomChannel及其Channel个孩子。
  • 在代码中的某处,您更改了子集合的引用myUserRoomChannel.setChannels(newChannelCollections)myUserRoomChannel.channels =new ChannelCollections();

  • 并尝试使用您的存储库删除该用户。

Hibernate记得用引用A设置子集合给用户可以再找到该集合,因为User.channels现在是User.channels == B(B是对你的集合的新引用)。

如何修复 找到你要替换孩子收藏的地方而不是:

  • myUserRoomChannel.setChannels(newChannelCollections)

  • myUserRoomChannel.channels =new ChannelCollections()

只是做

myUserRoomChannel.getChannels().add/delete/clearYourChannels()

答案 1 :(得分:0)

我刚刚完成了以下步骤,它完美无缺。

  • Reomve:
    • myUserRoomChannel.setChannels(channels)
  • 添加
    • myUserRoomChannel.getChannels().removeAll(channels)然后
    • userRoomChannelRepository.save(myUserRoomChannel)