1

I am migrating from the traditional JPA code base and facing a problem where a new entity cannot be saved by setting id to zero.

Here is my schema (PostreSQL):

CREATE TABLE my_user (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL
);

In JPA, i can set id to 0 and it will be considered as a new entity. A new id will be assigned automatically. However in R2DBC, new entities are always saved with id = 0, which is not possible.

I know, I can use Integer or Long for that and set them null, but I am using Kotlin and want to make id non-nullable. Otherwise I have to do a huge amount of unnessecary null checks.

userRepo.save(User(0, "A New User")) // works
userRepo.save(User(0, "Another New User")) // error, same id (but works in JPA)
@Table("my_user")
data class User(@Id var id: Int = 0,
                var name: String = "")
Tien Do Nam
  • 3,630
  • 3
  • 15
  • 30
  • Why would `0` be considered a new entity by JPA? And why would you need to make null checks for the primary key? You shouldn't be touching that at all in the code. – Kayaman Jun 06 '20 at 13:45
  • @Kayaman because I have to declare id nullable in my Kotlin code like `@Id var id: Int?`. And everytime I access the id, the Kotlin compiler forces me to check if it's null or not. In JPA, if id is primitive, then zero is considered as new – Tien Do Nam Jun 06 '20 at 13:48
  • But why are you accessing the `id`? It's a database primary key. Your application knows that it's null for new entities and non-null for existing entities, but it shouldn't assign it or access it. – Kayaman Jun 06 '20 at 13:51
  • Because I am dealing with foreign keys. e.g. `postRepo.save(Post(0, user.id, "Some Text"))`. There I am accessing `user.id` – Tien Do Nam Jun 06 '20 at 13:54
  • Seems to be because of different handling between [JPA and Spring Data](https://stackoverflow.com/questions/11283709/always-use-primitive-object-wrappers-for-jpa-id-instead-of-primitive-type). – Kayaman Jun 06 '20 at 14:03

1 Answers1

0

It seems that this issue will be fixed in Spring Boot 2.4

https://github.com/spring-projects/spring-data-r2dbc/issues/402

Tien Do Nam
  • 3,630
  • 3
  • 15
  • 30