简体   繁体   中英

How to insert an immutable record using spring-data-jdbc

Entity is

import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;

import java.util.UUID;

@Table
public record Picture(
        @Id UUID id,
        UUID galleryId,
        String metadata
) { }

Note that the ID is a UUID assigned client-side so I'm not interested in any sort of IDs assigned automagically by the database.

The repository:

import org.springframework.data.repository.CrudRepository;

public interface PictureRepository extends CrudRepository<Picture, String>, WithInsert<Picture> {
}
public interface WithInsert<T> {
    T insert(T t);
}
import org.springframework.data.jdbc.core.JdbcAggregateTemplate;

public class WithInsertImpl<T> implements WithInsert<T> {

    private final JdbcAggregateTemplate template;

    public WithInsertImpl(JdbcAggregateTemplate template) {
        this.template = template;
    }

    @Override
    public T insert(T t) {
        return template.insert(t);
    }
}

when I invoke repository.insert(picture) I end up with the following error:

 java.lang.UnsupportedOperationException: Cannot set immutable property [...package redacted away...].Picture.id!
    at org.springframework.data.mapping.model.BeanWrapper.setProperty(BeanWrapper.java:86) ~[spring-data-commons-2.2.6.RELEASE.jar!/:2.2.6.RELEASE]
    at org.springframework.data.mapping.model.ConvertingPropertyAccessor.setProperty(ConvertingPropertyAccessor.java:61) ~[spring-data-commons-2.2.6.RELEASE.jar!/:2.2.6.RELEASE]
    at org.springframework.data.relational.core.conversion.AggregateChange.setIdAndCascadingProperties(AggregateChange.java:177) ~[spring-data-relational-1.1.6.RELEASE.jar!/:1.1.6.RELEASE]
    at org.springframework.data.relational.core.conversion.AggregateChange.populateIdsIfNecessary(AggregateChange.java:144) ~[spring-data-relational-1.1.6.RELEASE.jar!/:1.1.6.RELEASE]

Question is: is there a way I can use immutable Entity with spring-data-jdbc?

Rant: immutability is good, UUIDs are good, auto-increment is bad. I think it's quite an assumption that I want auto-increment necessarily and I'd like to be able to shut it off in case I don't want it.

EDIT: I'm using spring-boot-starter-jdbc:2.2.6.RELEASE which comes with spring-data-jdbc:1.1.6.RELEASE

This bug was found and fixed during the work for version 2.0.0. of Spring Data JDBC.

If you still see this behaviour or need a backport to 1.1.x please create an issue on https://jira.spring.io/browse/DATAJDBC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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