简体   繁体   English

Spring R2DBC:如果 id 为零,则保存新实体

[英]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.我正在从传统的 JPA 代码库迁移,并面临一个问题,即无法通过将 id 设置为零来保存新实体。

Here is my schema (PostreSQL):这是我的架构(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.在 JPA 中,我可以将 id 设置为0 ,它将被视为一个新实体。 A new id will be assigned automatically.将自动分配一个新的 ID。 However in R2DBC, new entities are always saved with id = 0, which is not possible.然而在 R2DBC 中,新实体总是以 id = 0 保存,这是不可能的。

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.我知道,我可以使用IntegerLong并设置它们null ,但我正在使用 Kotlin 并希望使id不可为空。 Otherwise I have to do a huge amount of unnessecary null checks.否则我必须做大量不必要的 null 检查。

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

It seems that this issue will be fixed in Spring Boot 2.4似乎这个问题将在 Spring Boot 2.4 中修复

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM