【问题标题】:Creating an independent copy of the entity创建实体的独立副本
【发布时间】:2018-01-16 12:47:59
【问题描述】:

我正在创建一个新列表。我将对象从实体列表写入新列表。然后我会适当地从实体列表中清除项目,这也会导致从这个新列表中删除对象。

final ContributionEntity contributionEntity = this.findContribution(contributionId, DataStatus.WAITING, user, MovieField.PHOTO);

final Set<Long> idsToAddBeforeCleanUp = contributionEntity.getIdsToAdd();

this.cleanUpIdsToAdd(contributionEntity.getIdsToAdd(), contribution.getIdsToAdd(), contributionEntity.getMovie().getPhotos());

private void cleanUpIdsToAdd(final Set<Long> idsToAddFromEntity, final Set<Long> idsToAddFromDto,
                                 final List<? extends MovieInfoEntity> entities) {
        for (final Iterator<Long> it = idsToAddFromEntity.iterator(); it.hasNext(); ) {
            final Long id = it.next();
            if (!idsToAddFromDto.contains(id)) {
                it.remove();
                this.delete(entities, id);
            }
        }
    }

此代码从主题照片列表contributionEntity 中删除实体,但也从列表idsToAddBeforeCleanUp 中删除对象。

如何从实体复制列表并使其独立于该实体?我不想从列表中删除项目idsToAddBeforeCleanUp

【问题讨论】:

  • 几乎所有的 Set 和 List 实现都有一个复制构造函数,它将创建一个(浅)副本。

标签: java spring hibernate spring-mvc spring-boot


【解决方案1】:
final Set<Long> idsToAddBeforeCleanUp = new HashSet<>();   
contributionEntity.getIdsToAdd().foreach(item -> idsToAddBeforeCleanUp.add(item));

您并没有真正创建一个新系列,您只是对该系列进行了另一个引用。使用上面的代码,您可以创建一个新列表并且它应该可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-30
    • 2014-05-21
    • 2021-10-22
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    相关资源
    最近更新 更多