Search code examples
javaspringkotlinspring-data-r2dbcr2dbc

Spring R2DBC: Save new entity if id is zero


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 = "")

Solution

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

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