Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a record with custom id use Spring data jdbc?

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

like image 546
harrell hao Avatar asked Oct 12 '18 02:10

harrell hao


1 Answers

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());
            }
        }
    };
}

There is an example demonstrating that in the Spring Data Examples

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.

UPDATE

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.

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.

like image 51
Jens Schauder Avatar answered Sep 23 '22 16:09

Jens Schauder