密钥' PRIMARY'的重复实体。

时间:2017-10-16 13:47:07

标签: java mysql sql hibernate jpa

我的问题是,当我使级联持续时,它会抛出异常(MySQLIntegrityConstraintViolationException)。 我正在使用Spring Data;来保存我的数据。

  

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:   重复录入' Bloomberg'关键' PRIMARY'

News.class:

@Entity
public class News implements Serializable {

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

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "company_name")
    private Company company;

    ...
}

Company.class:

@Entity
@Table(name = "company")
public class Company implements Serializable{

    @Id
    @Column(unique = true,nullable = false)
    private String name;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "company",fetch = FetchType.EAGER)
    private List<News> newsList;

   ...
}

我正在使用此代码继续:

public void parseDB() throws IOException {
    List<News> newsList = new ArrayList<>();

    Map<String, Company> companyMap = ((List<Company>) companyRepository.findAll()).stream().collect(Collectors.toMap(Company::getName, company -> company));

    newsList.addAll(WebPagesParser.parseCategory("...", "...", companyMap));
    newsList.forEach(newsService::create);
    }


public static List<News> parseCategory(String url, String category,Map<String,Company> companyMap) throws IOException {
       ... 
      Company company; 
      if (companyMap.containsKey(name)) {
                    company = companyMap.get(name);
                } else {
                    company = new Company();
                    company.setName(top.get(1).text());
                }
       news.setCompany(company);
      ...
      }

它给了我新的例外

  

org.springframework.dao.InvalidDataAccessApiUsageException:已分离   实体传递给持久化:com.example.inosmi.database.data.News;   嵌套异常是org.hibernate.PersistentObjectException:detached   传递给实体的实体:com.example.inosmi.database.data.News

完成: 已经解决了我的一半问题,我仍然不知道它在哪里但它有效。谢谢大家!

2 个答案:

答案 0 :(得分:0)

MySQL告诉您正在尝试使用相同的主键插入多行

与此相关的代码在这里

@Id
@Column(unique = true, nullable = false)
private String name;

您加载的数据有多行,公司名称为Bloomberg

答案 1 :(得分:0)

为@OneToMany使用Set而不是List来维护一个index

@OneToMany(cascade = CascadeType.ALL, mappedBy = "company",fetch = FetchType.EAGER)
private Set<News> newsList;