MySQLIntegrityConstraintViolationException 解决办法

使用JPA做映射:

 

	/**
	 * 指标
	 */
	@OneToOne(optional = false, cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
	@JoinColumn(name = "indexItemId", referencedColumnName = "id", unique = true)
	private IndexItem indexItem;

 区在插入操作

 

	private void createPaperItem(IndexItem indexItem, Paper paper) {
		PaperItem paperItem = new PaperItem();
		paperItem.setPaper(paper);
		paperItem.setPaperItemName(indexItem.getIndexItemName());
		log.info("paperItemName" + indexItem.getIndexItemName());
		paperItem.setIndexItem(indexItem);
		paperItem.setAnswer(indexItem.getAnswer());
		paperItemManager.add(paperItem);
	}
 

的时候一直报如下的错:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '4' for key "indexItemId",

 

 自己估计是mysql的关键字原因,是否是自己占用了mysql的关键字,做了如下更改:

 

	@OneToOne(optional = false, cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
	@JoinColumn(name = "_indexItemId_", referencedColumnName = "id", unique = true)
	private IndexItem indexItem;

 同样还是报如下的错误:

 

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '4' for key "_indexItemId_",

不知道是什么原因,猜测是,Mysql的 indexItemId 的属性的值重复了但是自己做了一下Debug跟踪,没有重复的id,无奈的选择做了如下的修改:

 

	private void createPaperItem(IndexItem indexItem, Paper paper) {
		if (null != paperItemManager.query(indexItem)) {
			return;
		}
		PaperItem paperItem = new PaperItem();
		paperItem.setPaper(paper);
		paperItem.setPaperItemName(indexItem.getIndexItemName());
		log.info("paperItemName" + indexItem.getIndexItemName());
		paperItem.setIndexItem(indexItem);
		paperItem.setAnswer(indexItem.getAnswer());
		paperItemManager.add(paperItem);
	}

 结果不出错了,没有错误了也就懒得管是什么原因了,先敢时间要紧!

结论:肯定是有重复的indexItemId所造成的!

你可能感兴趣的:(mysql,jdbc,jpa)