如何使用JPA和Spring-Data-Jpa创建Map <integer,class =“”>关系

时间:2018-11-05 14:40:58

标签: hibernate jpa spring-data-jpa entitymanager

有2个实体:

public class Store {

    @GeneratedValue
    @Id
    protected Long id;

    @LazyCollection(LazyCollectionOption.EXTRA)
    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "STORE_ID")
    @Valid
    @MapKey(name = "id")
    protected Map<Long, Product> products = new HashMap<>();
}

public class Product {

    @Id
    protected Long id;
}

产品ID不是自动生成的,因此我必须手动获取它。

创建产品并保存它可以正常工作:

Product product = new Product();
product.setId(id); // id has been read from the sequence
productRepository.save(product);

但是,在创建商店时,如果我这样做:

Store store = new Store();
store.getProducts().put(product.getId(), product);
storeRepository.save(store);

我得到一个

EntityExistsException: A different object with the same identifier value was already associated with the session

但是,如果我这样做(在添加产品之前保存商店):

Store store = new Store();
storeRepository.save(store);
store.getProducts().put(product.getId(), product);
storeRepository.save(store);

有效。

有人可以解释为什么吗?

谢谢。

0 个答案:

没有答案