Spring Boot 保存新对象时React式资料档案库引发异常错误

xqkwcwgp  于 2022-11-23  发布在  Spring
关注(0)|答案(4)|浏览(160)

我正在使用r2dbcr2dbc-h2和实验性spring-boot-starter-data-r2dbc

implementation 'org.springframework.boot.experimental:spring-boot-starter-data-r2dbc:0.1.0.M1'
implementation 'org.springframework.data:spring-data-r2dbc:1.0.0.RELEASE' // starter-data provides old version
implementation 'io.r2dbc:r2dbc-h2:0.8.0.RELEASE'
implementation 'io.r2dbc:r2dbc-pool:0.8.0.RELEASE'

我创建了React式存储库

public interface IJsonComparisonRepository extends ReactiveCrudRepository<JsonComparisonResult, String> {}

还添加了一个自定义脚本,用于在启动时在H2中创建表

@SpringBootApplication
public class JsonComparisonApplication {
    public static void main(String[] args) {
        SpringApplication.run(JsonComparisonApplication.class, args);
    }

    @Bean
    public CommandLineRunner startup(DatabaseClient client) {
        return (args) -> client
            .execute(() -> {
                var resource = new ClassPathResource("ddl/script.sql");
                try (var is = new InputStreamReader(resource.getInputStream())) {
                    return FileCopyUtils.copyToString(is);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } })
            .then()
            .block();
    }
}

我的r2dbc配置如下所示

@Configuration
@EnableR2dbcRepositories
public class R2dbcConfiguration extends AbstractR2dbcConfiguration {
    @Override
    public ConnectionFactory connectionFactory() {
        return new H2ConnectionFactory(
            H2ConnectionConfiguration.builder()
                .url("mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE")
                .username("sa")
                .build());
    }
}

执行逻辑的服务如下所示

@Override
public Mono<JsonComparisonResult> updateOrCreateRightSide(String comparisonId, String json) {
    return updateComparisonSide(comparisonId, storedComparisonResult -> {
        storedComparisonResult.setRightSide(json);
        return storedComparisonResult;
    });
}

private Mono<JsonComparisonResult> updateComparisonSide(String comparisonId,
                                                        Function<JsonComparisonResult, JsonComparisonResult> updateSide) {
    return repository.findById(comparisonId)
        .defaultIfEmpty(createResult(comparisonId))
        .filter(result -> ComparisonDecision.NONE == result.getDecision()) // if not NONE - it means it was found and completed
        .switchIfEmpty(Mono.error(new NotUpdatableCompleteComparisonException(comparisonId)))
        .map(updateSide)
        .flatMap(repository::save);

}

private JsonComparisonResult createResult(String comparisonId) {
    LOGGER.info("Creating new comparison result: {}.", comparisonId);
    var newResult = new JsonComparisonResult();
    newResult.setDecision(ComparisonDecision.NONE);
    newResult.setComparisonId(comparisonId);
    return newResult;
}

域如下所示

@Table("json_comparison")
public class JsonComparisonResult {
    @Column("comparison_id")
    @Id
    private String comparisonId;
    @Column("left")
    private String leftSide;
    @Column("right")
    private String rightSide;
    // @Enumerated(EnumType.STRING) - no support for now
    @Column("decision")
    private ComparisonDecision decision;
    private String differences;

问题是,当我尝试向数据库中添加任何对象时,都会失败,并出现异常

org.springframework.dao.TransientDataAccessResourceException: Failed to update table [json_comparison]. Row with Id [4] does not exist.
    at org.springframework.data.r2dbc.repository.support.SimpleR2dbcRepository.lambda$save$0(SimpleR2dbcRepository.java:91) ~[spring-data-r2dbc-1.0.0.RELEASE.jar:1.0.0.RELEASE]
    at reactor.core.publisher.FluxHandle$HandleSubscriber.onNext(FluxHandle.java:96) ~[reactor-core-3.3.1.RELEASE.jar:3.3.1.RELEASE]
    at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:73) ~[reactor-core-3.3.1.RELEASE.jar:3.3.1.RELEASE]
    at reactor.core.publisher.MonoUsingWhen$MonoUsingWhenSubscriber.deferredComplete(MonoUsingWhen.java:276) ~[reactor-core-3.3.1.RELEASE.jar:3.3.1.RELEASE]
    at reactor.core.publisher.FluxUsingWhen$CommitInner.onComplete(FluxUsingWhen.java:536) ~[reactor-core-3.3.1.RELEASE.jar:3.3.1.RELEASE]
    at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onComplete(Operators.java:1858) ~[reactor-core-3.3.1.RELEASE.jar:3.3.1.RELEASE]
    at reactor.core.publisher.Operators.complete(Operators.java:132) ~[reactor-core-3.3.1.RELEASE.jar:3.3.1.RELEASE]
    at reactor.core.publisher.MonoEmpty.subscribe(MonoEmpty.java:45) ~[reactor-core-3.3.1.RELEASE.jar:3.3.1.RELEASE]
    at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.3.1.RELEASE.jar:3.3.1.RELEASE]

由于某种原因,在SimpleR2dbcRepository库类中的save期间,它不认为objectToSave是新的,但随后它无法更新,因为它实际上并不存在。

// SimpleR2dbcRepository#save
@Override
@Transactional
public <S extends T> Mono<S> save(S objectToSave) {

    Assert.notNull(objectToSave, "Object to save must not be null!");

    if (this.entity.isNew(objectToSave)) { // not new
        ....
    }
}

为什么会发生这种情况,问题是什么?

mzaanser

mzaanser1#

**TL;DR:**Spring Data如何知道您的对象是新的还是应该存在?

关系型Spring Data 仓库(JDBC和R2 DBC)必须在[Reactive]CrudRepository.save(…)上区分给定对象是新对象还是数据库中存在的对象。执行save(…)操作会导致INSERTUPDATE语句。发出错误的语句会导致主键冲突或空操作,因为标准SQL没有表达upsert的方法。
Spring Data JDBC|默认情况下,R2 DBC使用@Id值的存在/不存在。生成的主键是一种广泛使用的机制。如果提供了主键,则认为实体已存在。如果id值为null,则认为实体是新的。
请阅读参考文档中有关实体状态检测策略的详细信息。

waxmsbnn

waxmsbnn2#

因为已经提供了@ Id,所以必须实现Persistable。库需要判断该行是新的还是应该存在。如果实体实现了Persistable,那么保存(...)将使用isNew()的结果来决定是发出INSERT还是UPDATE。
例如:

public class Product implements Persistable<Integer> {

    @Id
    private Integer id;
    private String description;
    private Double price;

    @Transient
    private boolean newProduct;

    @Override
    @Transient
    public boolean isNew() {
        return this.newProduct || id == null;
    }

    public Product setAsNew() {
        this.newProduct = true;
        return this;
    }
}
arknldoa

arknldoa3#

也许你应该考虑到这一点:将ID/主键的数据类型选择为INT/LONG,并将其设置为AUTO_INCREMENT(如下所示):
创建表产品(标识INT主键AUTO_INCREMENT NOT NULL,模型名VARCHAR(30),年份VARCHAR(4),所有者VARCHAR(50));在发布请求正文中,不要包括ID字段。

kgqe7b3p

kgqe7b3p4#

正在删除@ID发出的insert语句

相关问题