4

I have a Springboot application that uses Spring Data. For test purposes only, I use an embedded H2 DB and load some initial data through a data.sql file. My entity are annotated with

@Id @GeneratedValue(strategy = GenerationType.AUTO) 

The problem I'm facing: for the generation of the ids (when I persist some objects), the id-values already used in my initial data (in data.sql) are NOT taken into consideration. As a result it comes to conflict, since it can happen that Hibernate try to use an Id already used. A solution would be to change the GenerationType into IDENTITY, but i'm reluctant to do so, since in production i would prefer having GenerationType.AUTO.

What is best practices to handle this?

6
  • 2
    Why do you prefer AUTO over IDENTITY. It seems to me that an identity/auto increment column is what you need here. Commented Sep 9, 2019 at 13:56
  • In production i'm using a postgreSQL DB, and i was a bit afraid of having a mess with postgres If I use IDENTITY. Commented Sep 9, 2019 at 14:08
  • Well I think the better strategy is to let Postgres worry about managing the column. Hibernate is just a thin layer in Java, sitting on top of JDBC, which in turn sits on top of your database. Commented Sep 9, 2019 at 14:10
  • ok thanks, i will switch to IDENTITY then Commented Sep 9, 2019 at 14:36
  • Use a wraper class (Integer, Long) in this way hibernate will use a null value and the bd will create the next id. hibernate automatically will load the created value Commented Sep 9, 2019 at 19:24

1 Answer 1

6

Tim Biegeleisen seemed to already have convinced you: Use IDENTITY which seems to work in both cases.

The alternative I would recommend nowadays is to use Testcontainers with Postgres in the test and drop H2.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it seems interessant indeed and i will consider giving it a try for my next project.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.