【发布时间】:2019-01-21 12:31:58
【问题描述】:
我正在尝试自学一点 Java 和 JPA,现在是从几天以来什么都没有发生的地步。
我有两个通过 OneToMany 关系链接的实体(ITEM 和 ITMLIST)。
我将 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 中的代码。
【问题讨论】:
-
看看this,也许会有帮助!
-
从 @OneToMany 更改为 @ManyToMany 后,目前一切正常
标签: java jpa one-to-many persist mysql-error-1062