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

时间:2018-08-14 15:31:48

标签: java jpa one-to-many persist mysql-error-1062

我正在尝试自学Java和JPA,现在这是几天以来什么都没发生的地方。

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

我将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

启动应用程序并将ITEM放在ITEMLIST之前的ITEMLIST中时,ITEMLIST_ITEM表中会出现错误。

我的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;
}

我的ITEMLIST实体:

@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中的代码。

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

这可能是因为,当要保存您的ItemSet时,您试图保留该Set的相同Item值,而您不能这样做。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

相关问题