如何使用Spring Data JDBC插入具有自定义ID的记录? [英] How to insert a record with custom id use Spring data jdbc?

查看:569
本文介绍了如何使用Spring Data JDBC插入具有自定义ID的记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Spring Data JPA,我可以使用批注@GeneratedValue(strategy = GenerationType.AUTO)插入具有自定义ID的记录,但是对于Spring Data JDBC,如何插入具有自定义ID的记录?我曾尝试用id插入,但没有引发任何异常,并且记录未插入表中.

For Spring Data JPA, I can use annotation @GeneratedValue(strategy = GenerationType.AUTO) insert a record with custom id, but for Spring Data JDBC, how to insert a record with custom id? I had tried to insert with id, but no any exception threw, and the record is not inserted into the table.

推荐答案

使用Spring Data JDBC做到这一点的方法是注册一个BeforeSaveEvent ApplicationListener来创建id并将其设置在实体中.

The way to do that with Spring Data JDBC is to register a BeforeSaveEvent ApplicationListener that creates the id and sets it in the entity.

@Bean
public ApplicationListener<BeforeSaveEvent> idSetting() {

    return event -> {

        if (event.getEntity() instanceof LegoSet) {

            LegoSet legoSet = (LegoSet) event.getEntity();
            if (legoSet.getId() == null) {
                legoSet.setId(createNewId());
            }
        }
    };
}

未在表中插入行,但也没有得到异常的原因是:Spring Data JDBC得出结论,自从设置ID并执行更新以来,该实体已经存在. 但是由于它不存在,所以更新无法更新任何行,因此什么也没发生. 可能值得创建一个改进请求,以将更新计数检查为0.

The reason your row wasn't inserted in the table, but you also didn't get an exception is: Spring Data JDBC concluded that the entity already existed since the ID was set and performed an update. But since it didn't exist the update failed to update any rows, so nothing happened. It might be worth creating an improvement request to check the update count against 0.

更新

从1.1版开始

Since version 1.1 JdbcAggregateTemplate.insert is available allowing you do an insert without any check if an aggregate is new. You can use that to create a custom method in your repository, if you want, or you can autowire the template wherever you need it and use it directly.

对于DATAJDBC-438,如果保存了聚合,Spring Data JDBC也会引发异常,从而导致更新,但是更新更新了零行,因此这种问题不会引起人们的注意.

Also with DATAJDBC-438 Spring Data JDBC will throw an exception if an aggregate is saved, resulting in an update but the update updates zero rows so this kind of problem doesn't get unnoticed.

这篇关于如何使用Spring Data JDBC插入具有自定义ID的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆