0

I have 3 rows already imported (by import.sql in class path) in my database with primary keys id=1, id=2, id=3. When I try to insert new data (through javax.faces), I get ConstraintViolationException 3 times in a row, and then, on the 4th try, new row is inserted with autogenerated id=4. Is there any possibility to avoid those 3 errors and insert data on a first try with id starting from last id in a table?

Here is my entity declaration:

@Entity
@Table(name = "book")
public class Book {

   @Id
   @GeneratedValue
   @Column(name = "id")
   private long id;
}

Thank you in advance.

anigsu
  • 11
  • 1
  • If you import data directly into the table, not via Hibernate, then Hibernate does not know about it and does not update the counters for autogenerated `@Id @GeneratedValue` and is trying to assign numbers which were already used by you during the import. In your case, since you didn't explicitely specify a [generation strategy](https://thoughts-on-java.org/jpa-generate-primary-keys/), then Hibernate choosed one itself - identity, sequence or table. You need to update the conters itself - depending on the used strategy, change the sequence or update the table. – krokodilko Jan 05 '19 at 17:00

1 Answers1

0

Thank you, krokodilko. Solved it by adding strategy:

@GeneratedValue(strategy=GenerationType.SEQUENCE)

and adding this line after every table insert in import.sql script:

SELECT setval([sequencename], max(id)) FROM [tablename];
anigsu
  • 11
  • 1