Reputation: 99
When testing my application in Swagger and trying to post one entry to MySQL database, I keep getting an error saying: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '0' for key 'PRIMARY'.
When checking my stack trace, I can see the following lines before my application throws an error message:
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
It seems like there is something wrong with my entries mapping. My entry Counterparty contains an entry Address (one-to-one relation)
@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;
Both of those entries are parts of my Invoice entry. Maybe I made a mistake while referring from one table to another?
Upvotes: 0
Views: 29616
Reputation: 369
I think the problem lies in AutoGeneration... did you manually create the TABLE or did you allow Hibernate to do it for you...
If you have Created the DB Table manually, you must have forgotten to AUTO increment the ID.
1. Try adding AutoGeneration to ID on address table too...
@Id
@Column(name = "address_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
ALTER TABLE table_name MODIFY column_name INTEGER NOT NULL AUTO_INCREMENT;
Upvotes: 7