JPA 2 @SequenceGenerator @GeneratedValue producing unique constraint violation
Yes, your analysis is correct. You identified correctly the problem (we had a similar problem). And... if you gonna put that in production, don't forget to:
- either generate manually the sequence table for the new sequence generator WITH the correct initial value/initial ID (otherwise hibernate will begin from 1 and you will get again )
- or set that value in Code (check
initalValue
in@SequenceGenerator
).
I am not able to enumerate the best practices, but I suppose you could lower the limit of 50. Also I do not have experience with PostgreSQL, but in MySQL you have a simple table for the seq. generator and hibernate makes the entire stuff.
Had a same problem — for some reason hibernate wasn't picked the right number from the sequence. Tried all approaches with no luck and finally came to this solution:
@Entity
@Table(name = "events")
@SequenceGenerator(name = "events_id_seq", sequenceName = "events_id_seq", allocationSize = 1)
public class Event {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "events_id_seq")
private BigInteger id;
I've had to put @SequenceGenerator on top of class, not the method, also allocation size was set to 1 (if you'll left this value as default, it will start to produce negative ids).
spring-data-jpa 2.1.2
, hibernate 5.3.7
, pg 42.2.5