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

徘徊边缘 提交于 2019-12-23 10:18:04

问题


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.


回答1:


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.




回答2:


I found another way to solve this problem although it's a little trouble.

// BaseEntity
public class BaseEntity implements Persistable, Serializable {

    @Id
    String id;

    @Transient
    @JsonIgnore
    private boolean newEntity;

    @Override
    public Object getId() {
        return id;
    }

    public void setNew(boolean newInstance) {
        this.newEntity = newInstance;
    }

    @Override
    @JsonIgnore
    public boolean isNew() {
        return newEntity;
    }
}

// User
User extends BaseEntity
...


// insert
User user = new User();
user.id = "5bffb39cc5e30ba067e86dff";
user.setName("xiangzi");
user.setNew(true);
userRepository.save(user);


// update
User user = new User();
user.id = "5bffb39cc5e30ba067e86dff";
user.setName("xiangzi2");
userRepository.save(user);

When insert needs to add the line user.setNew(true);.

Thanks!

I also added a comment here.



来源:https://stackoverflow.com/questions/52771309/how-to-insert-a-record-with-custom-id-use-spring-data-jdbc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!