javajpaone-to-manypersistmysql-error-1062

JPA: SQL Error: 1062, SQLState: 23000 ERROR: Duplicate entry:


i'm trying to teach myself a little bit Java and JPA and now is the point where nothing happens since days.

I have two entities (ITEM and ITEMLIST) linked by a OneToMany relationship.

I persisted the ITEM to the database separately.

The Goal is to get a table with a primary key of the ITEMLIST with the foreign keys of the ITEMS.

But when I save a second ITEMLIST the “duplicate...” error occurs.

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

When I start the app and put an ITEM in the ITEMLIST that was befor in a ITEMLIST, the error arises in the ITEMLIST_ITEM table.

My ITEM entity:

@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;
}

My ITEMLIST entity:

@Entity
public class ItemList implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@OneToMany
private Set<Item> itemInList;

public ItemList() {
    itemInList = new HashSet<>();
}

My methods to persist the entities:

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();
    }
}

Help is welcome, even if it's the code in generell.


Solution

  • I solved this problem by changing the relationship to @ManyToMany. In my case it works.