Home > Net >  Spring Boot JPA how to handle @Id if I use composite key
Spring Boot JPA how to handle @Id if I use composite key

Time:04-03

I am running a Spring Boot application were I use JPA. I am using Postgresql as DB.

I get some data from an api where there is no Id for each row. So I have to use @Id and @GeneratedValue. But my problem is that when I request this data again I might get the exact same rows or some of them again. I can make a composite key that consist of 3 of the columns but then how do I do with the Id that I would like to keep (autogenerated value). If I understand correct, I can´t use composite primary key and a generate @Id at the same time?

An extension of this question is that sometimes a column in each row are updated. Then I would like to update only this column and not create a new row in the DB. I could make a modified query that checks if the three column (composite key) already exist then I update that row if any change or if row is missing just save. Or is their any other option that I have missed so I do not have to write any query myself?

CodePudding user response:

You are correct, you have to decide if you want to use a single autogenerated Id or a composite key, you can't have both at the same time. And if your API can't handle a single Id you are probably better of doing as you are thinking in your extended question; creating a composite key and when updating rows check for a row that match your three values.

  • Related