我正在尝试教自己一些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 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中的代码。