在Swagger中测试我的应用程序并尝试将一个条目发布到MySQL数据库时,我不断收到错误消息:java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '0' for key 'PRIMARY'.
检查我的堆栈跟踪时,在应用程序抛出错误消息之前,我可以看到以下行:
2017-09-12 12:55:11.394 INFO 642 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 28 ms
Hibernate: insert into addresses (house_number, street_name, town_name, zip_code, address_id) values (?, ?, ?, ?, ?)
2017-09-12 12:55:16.562 WARN 642 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1062, SQLState: 23000
2017-09-12 12:55:16.562 ERROR 642 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : Duplicate entry '0' for key 'PRIMARY'
2017-09-12 12:55:16.563 INFO 642 --- [nio-8080-exec-4] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
我的条目映射似乎有问题。我的条目Counterparty包含一个条目地址(一对一关系)
@Entity
@Table(name = "counterparties")
public class Counterparty implements Serializable {
@Id
@Column(name = "counterparty_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int nip;
private String companyName;
private String phoneNumber;
private String bankName;
private String bankNumber;
@OneToOne(cascade = {CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH, CascadeType.REFRESH})
@JoinColumn(name = "address_id", referencedColumnName="address_id")
private Address address;
@OneToMany(mappedBy = "counterparty", fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH, CascadeType.REFRESH})
@JsonIgnore
private List<Invoice> invoices;
@Entity
@Table(name = "addresses")
public class Address implements Serializable {
@Id
@Column(name = "address_id")
private int id;
private String zipCode;
private String townName;
private String streetName;
private String houseNumber;
@OneToOne(mappedBy = "address", cascade = {CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH, CascadeType.REFRESH})
@JsonIgnore
private Counterparty counterparty;
这两个条目都是我的发票条目的一部分。也许我在从一张桌子转到另一张桌子时犯了错误?
答案 0 :(得分:1)
我认为问题在于AutoGeneration ...您是否手动创建了TABLE或者您是否允许Hibernate为您执行此操作...
如果您手动创建了数据库表,则必须忘记自动增加ID。
1.尝试将AutoGeneration添加到地址表上的ID ...
@Id
@Column(name = "address_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
ALTER TABLE table_name MODIFY column_name INTEGER NOT NULL AUTO_INCREMENT;
答案 1 :(得分:1)
我也遇到过类似的情况,解决了spring批量重复输入的问题。 您可以找到解决方案 here