我的问题是,当我使级联持续存在时,它会抛出异常( MySQLIntegrityConstraintViolationException
)。
我正在使用Spring Data;
用于保存我的数据。
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'Bloomberg' for key 'PRIMARY'
新闻类:
@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;
...
}
公司类别:
@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);
...
}
它给了我新的异常(exception)
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.example.inosmi.database.data.News; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.example.inosmi.database.data.News
完成: 已经解决了一半的问题,我仍然不知道它在哪里,但它有效。谢谢大家!
最佳答案
MySQL 告诉您正在尝试插入具有相同主键的多行
与此相关的代码在这里
@Id
@Column(unique = true, nullable = false)
private String name;
您正在加载的数据有多行带有公司名称 Bloomberg
关于java - 键 'PRIMARY' 的重复实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46771910/