JPA使用Map 而不是列表

问题描述 投票:2回答:1

我正在使用Spring JPA来设计电子商务应用程序。假设我有两个类ProductOption与一对多关系,即Product将有许多OptionOption只属于一个Product。有了这个,典型的JPA映射就是

@Entity(name = "products")
class Product {
    @Id
    @Column(name = "product_id")
    private Long productId;

    @OneToMany(cascade = ALL, orphanRemoval = true)
    @JoinColumn(name = "product_id")
    private List<Option> options;

    // getters, setters
}

请注意options的类型是List<Option>。我想在这里使用Map而不是列表。

    @OneToMany(cascade = ALL, orphanRemoval = true)
    @JoinColumn(name = "product_id")
    @MapKey(name = "optionId")
    @MapKeyClass(Long.class)
    private Map<Long, Option> options;

使用Map,我认为它对更新和删除选项很有用。例如,通过使用List<Option>,当我想从Option删除Product给出一个选项id,我会做

public void deleteOption(Long productId, Long optionId) {
    Product p = productRepository.findByProductId(productId);
    List<Option> options = p.getOptions();
    Option toBeRemoved = null;
    for (Option o : options) {
       if (o.getOptionId == optionId) {
          toBeRemoved = o;
       }
    }
    options.remove(toBeRemoved);
    productRepository.save(p);
}

但如果我使用Map,它会更容易。

public void deleteOption(Long productId, Long optionId) {
    Product p = productRepository.findByProductId(productId);
    p.getOptions.remove(optionId);
    productRepository.save(p);
}

问题

一般来说,是否有理由使用List<Entity>而不是Map<Long, Entity>进行一对多关联?我可以一直使用Map吗?

java spring hibernate jpa
1个回答
1
投票

我认为你可以使用List和删除选项使用removeIf()方法。 @JB Nizet说,最好还是使用Set避免重复选项。

p.getOptions().removeIf(option->option.getOptionId().equals(optionId));
© www.soinside.com 2019 - 2024. All rights reserved.