0

I am using Spring Boot 2 for creating microservices. I have a scenario to save an entity. In entity for Id column I have added like below

@Id
@GeneratedValue(Strategy=GenerationType.Auto, generator="increment")
@GenericGenerator(name="increment", strategy="increment")
@Column(name="Id", insertable=false)
private Integer id;

Above works sometimes and it throws Primary Key Constraint Violation Exception sometimes. It is not consistent though. I am running it as two instances with different ports.

Error I get is unique constraint violated:

ConstraintViolationException: could not execute statement; constraint [primary_key_cons]; nested exception is ConstraintViolationException.

Only option I have is to change the strategy to sequence.

halfer
  • 19,824
  • 17
  • 99
  • 186
Lolly
  • 34,250
  • 42
  • 115
  • 150

2 Answers2

0

Did you insert some data manually? Maybe hibernate is generating id values which are already existing in db. If you can, just clear that table and test it again

Krzysztof K
  • 736
  • 4
  • 19
0

Don't use generic generator with strategy increment. It is not recommended to use in a cluster.

increment generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster.

for more info - here

Use GenerationType.SEQUENCE and crate a SequenceGenerator.

Example,

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "YourSequenceGenerator")
@SequenceGenerator(sequenceName = "YourSequence", name = "YourSequenceGenerator", allocationSize = 1)
private Integer id;
ray
  • 1,512
  • 4
  • 11