JPA: SQL 错误: 1062, SQLState: 23000 错误: 重复条目:.



我正在尝试自学一点Java和JPA,现在是几天来什么都没有发生的地步。

我有两个实体(ITEM 和 ITEMLIST(通过 OneToMany 关系链接。

我将 ITEM 分别保存到数据库中。

目标是获取一个表,其中包含 ITEMLIST 的主键和 ITEMS 的外键。

但是当我保存第二个 ITEMLIST 时,"重复..."发生错误。

WARN: SQL Error: 1062, SQLState: 23000
ERROR: Duplicate entry '1' for key 'xxxxx'
Information: HHH000010: On release of batch it still contained JDBC statements
Information: ERROR: javax.persistence.RollbackException: Error while committing the transaction

当我启动应用程序并将项目放入项列表中时,ITEMLIST_ITEM表中会出现错误。

我的项目实体:

@Entity
public class Item implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String description;
private double price;
public Item(String name, String description, double price) {
this.name = name;
this.description = description;
this.price = price;
}

我的项列表实体:

@Entity
public class ItemList implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@OneToMany
private Set<Item> itemInList;
public ItemList() {
itemInList = new HashSet<>();
}

我保留实体的方法:

public void saveItem(Item item) {
EntityManager em = EntityFactory.getEntityManager();       
try {
em.getTransaction().begin();      
em.persist(item);                      
em.getTransaction().commit();
} catch (EntityExistsException e) {
System.out.println(e);
} finally {
em.close();
}
}
public void saveItemList(ItemList itemlist) {
EntityManager em = EntityFactory.getEntityManager();
try {
em.getTransaction().begin();                           
em.merge(itemlist);
em.getTransaction().commit();
} catch (EntityExistsException e) {
System.out.println(e);
} finally {
em.close();
}
}

欢迎帮助,即使它是 generell 中的代码。

我通过将关系更改为@ManyToMany来解决此问题。就我而言,它有效。

这可能是因为在保存 ItemSet 时,您正在尝试保留此集的相同 Item 值,而您无法这样做。

您需要使用唯一 ID 保存在数据库中。 在数据库中保存主键时,主键可能会重复。尝试执行自动递增 ID

错误表明您输入的内容,即键"xxxxxx"是重复值。该值存在于数据库中,并且您不会为该键保存任何重复值。 为避免此错误,您不应提供任何重复值,否则必须允许重复值保存该"xxxxx"键的数据。

相关内容

最新更新