Rishi
Rishi

Reputation: 51

How to use my own save declaration instead of the one by Spring Data?

I have an upgrade in spring-boot from 1.5 to 2.1 and one of the CRUDRepository method save() is changed to saveAll which as the return type changes. Can some one let me know how to return the saveAll instead of save.

I have tried to create a wrapper which extends the save() to saveAll().

Upvotes: 0

Views: 114

Answers (1)

Nikolai  Shevchenko
Nikolai Shevchenko

Reputation: 7521

Something like this

@NoRepositoryBean
public interface BaseJpaRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {

    <S extends T> List<S> save(Iterable<S> entities);
}

@NoRepositoryBean
public class BaseJpaRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements BaseJpaRepository<T, ID> {

    private final EntityManager em;

    public BaseJpaRepositoryImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager em) {
        super(entityInformation, em);
        this.em = em;
    }

    @Override
    public <S extends T> List<S> save(Iterable<S> entities) {
        return saveAll(entities);
    }
}

Then derive Repository class(-es) from new BaseJpaRepository interface

@Repository
public interface MyEntityRepository extends BaseJpaRepository<MyEntity, Long> {

}

And finally in configuration class

@EnableJpaRepositories(
        basePackages = { ... },
        repositoryBaseClass = BaseJpaRepositoryImpl.class
)
public class RepoConfiguration {
...
}

Upvotes: 1

Related Questions