我的問題是,當我使級聯持續存在時,它會拋出異常(MySQLIntegrityConstraintViolationException
)。 我正在使用Spring Data;
來保存我的數據。重複鍵「PRIMARY」的實體
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 重複項 '彭博社' 重點 '主要'
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:獨立被persist 實體:com.example.inosmi.database.data.News; 嵌套的例外是org.hibernate.PersistentObjectException:被persist分離 實體:com.example.inosmi.database.data.News
完成: 已經解決了我的問題的一半,我還是不要」不知道它在哪裏,但它工作。感謝大家!
您正試圖插入一個已存在於數據庫中的主鍵。 –
我想合併它,但它沒有。 –
如果你使用一個和你的合併/持久代碼,你可以告訴我們你的查詢嗎? – LenglBoy