JPARepository-有时创建重复记录

时间:2020-02-24 13:08:01

标签: jpa spring-data-jpa

我有以下实体类。


@Data
@EqualsAndHashCode(callSuper=false)
@ToString(callSuper=true)
@Entity
@Table(name = "storeitem")
public class StoreItem extends SellableStoreItem {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private UUID id;

  @EqualsAndHashCode.Exclude
  @ToString.Exclude
  @ManyToOne
  @JoinColumn(name = "store_id")
  private Store store;

  @EqualsAndHashCode.Exclude
  @ToString.Exclude
  @ManyToOne
  @JoinColumn(name = "storeitemcategory_id", nullable = true)
  private StoreItemCategory storeItemCategory;

  @EqualsAndHashCode.Exclude
  @OneToMany(fetch = FetchType.EAGER, mappedBy = "storeItem")
  private List<StoreItemTranslation> storeItemTranslationList = new ArrayList<>();

  @EqualsAndHashCode.Exclude
  @OneToMany(mappedBy = "storeItem",
      cascade = CascadeType.ALL,
      orphanRemoval = true)
  private List<StoreItemOptionCollectionSelection> storeItemOptionCollectionSelections = new ArrayList<>();

  @EqualsAndHashCode.Exclude
  @Column(name = "uid")
  private UUID uid = UUID.randomUUID();

  @EqualsAndHashCode.Exclude
  @CreationTimestamp
  @Column(name = "createddate", nullable = false)
  private LocalDateTime createdDate;

  @EqualsAndHashCode.Exclude
  @Column(name = "iscurrent", nullable = false)
  private boolean isCurrent = true;

然后在我的服务层中,执行以下操作。


  private StoreItemResponse setStoreItemCreate(StoreItemDTO storeItemDTO, Store store, StoreItemCategory storeItemCategory) {

    StoreItem storeItem = new StoreItem(storeItemDTO, store, storeItemCategory);
    if(storeItemDTO.getUid() != null){
      storeItem.setUid(storeItemDTO.getUid());
    }
    storeItem = storeItemRepository.save(storeItem);

    // Create Translations for store Item
    for (TranslationDTO translationDTO : storeItemDTO.getTranslationDTOs()) {
      StoreItemTranslation translation = new StoreItemTranslation(translationDTO, storeItem);
      storeItemTranslationRepository.save(translation);
    }


    return new StoreItemResponse(storeItem.getId(), DtoResponseStatus.OK);
  }

但是,在测试代码时,我注意到有时(不经常但在某些情况下)我看到重复的记录(具有不同的ID)正在保存到数据库中。并且重复项之间的间隔为2ms,因此我怀疑storeItem = storeItemRepository.save(storeItem);创建了重复的记录。

为什么会这样?

0 个答案:

没有答案