Khai Ly
Khai Ly

Reputation: 145

How to retrieve a generated ID when saving objects with Spring Data R2DBC using Postgresql

Could you please help me to solve the problem below

I have a entity class:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    @Id
    private Long id;
    private String name;
}

and I save it in Postgresql with the code:

public Mono<User> save(User user){
        return databaseClient().inTransaction(db -> {
            return db
                .insert()
                .into(User.class)
                .using(user)
                //todo: return saved user
        });
}

I wish to get saved User, how I can do

Upvotes: 4

Views: 9233

Answers (1)

mp911de
mp911de

Reputation: 18119

Spring Data R2DBC expects your database to return generated keys. When using Postgres, then make sure to declare a column that generates Id's itself such as SERIAL.

In your case that would be:

CREATE TABLE user (
    id          serial CONSTRAINT id PRIMARY KEY,
    name        varchar(255) NOT NULL,
);

Depending on which API you're using, you can retrieve the Id with various approaches:

  • DatabaseClient: An INSERT operation returns generated values as Map<String, Object> by mapping column names to values. You need to extract the Id yourself.
  • Using R2dbcRepository: Saving a new object returns a Mono<T> that emits the saved (updated) object which contains a generated Id.

In general, we recommend immutable objects to avoid visibility and shared mutable state issues. Spring Data leverages Lombok's @Wither pattern to create a new object instance when Spring Data needs to propagate data back to an object.

See also:

Upvotes: 5

Related Questions