实体是
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
) { }
请注意,该 ID 是客户端分配的 UUID,因此我对数据库自动分配的任何类型的 ID 不感兴趣。
存储库:
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);
}
}
当我调用时,repository.insert(picture)
我最终得到以下错误:
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]
问题是:有没有办法可以将不可变实体与 spring-data-jdbc 一起使用?
咆哮:不变性很好,UUID 很好,自动增量很糟糕。我认为这是一个假设,即我必然需要自动增量,并且我希望能够关闭它以防万一我不想要它。
编辑:我正在使用 spring-boot-starter-jdbc:2.2.6.RELEASE 它附带 spring-data-jdbc:1.1.6.RELEASE