我正在尝试自学一点Java和JPA,现在是几天没有任何事情发生的地方。
我有两个实体(ITEM和ITEMLIST)通过OneToMany关系链接。
我将ITEM分别保存到数据库中。
目标是使用ITEMS的外键获取带有ITEMLIST主键的表。
但是,当我保存第二个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中的代码。
您需要使用唯一ID保存在数据库中。在数据库中保存时,您的主键可能会重复。尝试执行自动增量ID
这可能是因为在保存您的ItemSet时,您试图保留此Set的相同Item值,这是您无法做到的。
我通过改变与@ManyToMany的关系解决了这个问题。就我而言,它有效。