我正在使用Spring JPA来设计电子商务应用程序。假设我有两个类Product
和Option
与一对多关系,即Product
将有许多Option
和Option
只属于一个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
吗?
我认为你可以使用List
和删除选项使用removeIf()
方法。 @JB Nizet说,最好还是使用Set
避免重复选项。
p.getOptions().removeIf(option->option.getOptionId().equals(optionId));