使用@OneToMany JPA映射克隆管理实体

时间:2018-01-24 13:16:23

标签: java hibernate jpa clone one-to-many

鉴于我有3个带有@OneToMany双向映射的JPA实体,而MyEntity是根级实体:

@Entity
public class MyEntity extends AbstractEntity<Long> {

    @OneToMany(mappedBy = "myEntity", cascade = ALL, orphanRemoval = true)
    private List<OtherEntity> otherEntities = new LinkedList<>();

}

@Entity
public class OtherEntity extends AbstractEntity<Long> {

    @ManyToOne
    private MyEntity myEntity;

    @OneToMany(mappedBy = "otherEntity", cascade = ALL, orphanRemoval = true)
    private List<YetAnotherEntity> yetAnotherEntities = new LinkedList<>();

}

@Entity
public class YetAnotherEntity extends AbstractEntity<Long> {

    @ManyToOne
    private OtherEntity otherEntity;

}

我想创建MyEntity的副本,根据过滤条件删除少数OtherEntity,然后使用Jackson将其序列化为OutputStream(导出)

我怎样才能实现它?

我试图使用:

@PersistenceContext
private EntityManager em;

并致电:em.detach(myEntity);,但这会产生org.hibernate.AssertionFailure: possible non-threadsafe access to session

编辑: 添加导出服务方法:

@Override
public void export(MyEntity myEntity, OutputStream out) throws IOException {

    em.detach(myEntity);

    MyEntity myEntityToBeExported = new MyEntity();
    // filter out OtherEntities which we don't want to export
    List<OtherEntity> filteredOtherEntities = myEntity.getOtherEntities().stream()
            .filter(otherEntity -> ...)
            .collect(Collectors.toList());
    myEntityToBeExported.addOtherEntities(filteredOtherEntities);

    ObjectMapper mapper = mapperProvider.mapper();
    mapper.writeValue(out, myEntityToBeExported);
}

0 个答案:

没有答案