org.postgresql.util.psqlexception:错误:重复键值违反唯一约束“\u pkey”

2jcobegt  于 2021-07-14  发布在  Java
关注(0)|答案(0)|浏览(271)

当我尝试用一对多的关系更新两个实体时,我得到了这个错误。
这是第一个实体类:

package com.example.demo.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.SelectBeforeUpdate;

@Entity
@Table(name = "tags", schema = "public")
@NoArgsConstructor
@SelectBeforeUpdate
@Data
public class Tag {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(unique = true, nullable = false)
  private Long id;

  @Column(name = "tag")
  private String tag;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "product_id", nullable = false)
  private Product product;

  public Tag(String tag, Product product) {
    this.tag = tag;
    this.product = product;
  }
}

这是第二个实体类:

package com.example.demo.entity;

import com.example.demo.dto.ProductDto;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

@Entity
@NoArgsConstructor
@Table(name = "products", schema = "public")
@Data
public class Product {

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

  @Column(name = "name")
  private String name;

  @Column(name = "price")
  private double price;

  @Column(name = "added")
  private Date added;

  @OneToMany(mappedBy = "product", cascade = CascadeType.MERGE, orphanRemoval = true)
  @Fetch(value = FetchMode.SELECT)
  private List<Tag> tags;

  public Product(final ProductDto productDto) {
    this.id = productDto.getId();
    this.name = productDto.getName();
    this.price = productDto.getPrice();
    this.added = new Date(productDto.getAdded());
    this.tags = convertTagDtoToTag(productDto.getTags());
  }

  public List<Tag> convertTagDtoToTag(final List<String> tagDtos) {
    return tagDtos
        .stream()
        .map(t -> new Tag(t, this))
        .collect(Collectors.toList());
  }
}

我尝试更新的方法:

public Product updateProduct(final ProductDto productDto) {
    final Product product = this.productRepository.findById(productDto.getId()).map(p -> {
      p.setName(productDto.getName());
      p.setPrice(productDto.getPrice());
      p.setAdded(new Date(productDto.getAdded()));
      p.getTags().clear();
      p.getTags().addAll(p.convertTagDtoToTag(productDto.getTags()));

      return p;
    }).orElse(null);

    return this.productRepository.save(product);
  }

我得到一个错误:

org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "tags_pkey"
  Detail: Key (id)=(1) already exists.

我写这个方法,但我认为有更好的方法。

public Product updateProduct(final ProductDto productDto) {
    final Product product = this.productRepository.findById(productDto.getId()).map(p -> {
      p.setName(productDto.getName());
      p.setPrice(productDto.getPrice());
      p.setAdded(new Date(productDto.getAdded()));
      updateTag(p.getTags(), p.convertTagDtoToTag(productDto.getTags()));

      return p;
    }).orElse(null);

    return this.productRepository.save(product);
  }

  private void updateTag(List<Tag> serverTags, List<Tag> frontedTags) {
    for (int i = 0; i < serverTags.size(); i++) {
      serverTags.get(i).setTag(frontedTags.get(i).getTag());
    }
  }

我还有data.sql文件

INSERT INTO products (id, name, price, added) values (1, 'First product', 100, '2000-09-01');

INSERT INTO products (id, name, price, added)
values (2, 'Second product', 200, '2010-10-11');

INSERT INTO products (id, name, price, added)
values (3, 'Third product', 300, '2010-11-04');

INSERT INTO tags (id, tag, product_id)
values (1, 'tag1', 1);

INSERT INTO tags (id, tag, product_id)
values (2, 'tag2', 1);

INSERT INTO tags (id, tag, product_id)
values (3, 'tag3', 1);

INSERT INTO tags (id, tag, product_id)
values (4, 'tag4', 2);

INSERT INTO tags (id, tag, product_id)
values (5, 'tag5', 3);

看起来你的帖子大部分都是代码;请补充一些细节。看起来你的帖子大部分都是代码;请补充一些细节。看起来你的帖子大部分都是代码;请补充一些细节。看起来你的帖子大部分都是代码;请补充一些细节。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题