Home > Net >  How to make multiple save methods in spring data JPA?
How to make multiple save methods in spring data JPA?

Time:11-21

I had a slow performance of default save method in spring data jpa. So, i decided to make save method work asynchronously cause i did not need response in this specific method.

@Repository
public interface WorkplaceRepo extends JpaRepository<Workplace, Long> {
    @Async
    public <S extends Workplace> S save(S workplaceE);

It caused the problem that all save methods in whole project started to call this asynchronous method. The question is: how to use both save methods without losing one of them(default version and async version)

i thought to create custom insert method using native query, but the entity have so many columns and foreign keys, and i am not sure that it would work correctly.

CodePudding user response:

I would suggest creating new repository WorkplaceRepoAsync with one save method something like this:

@Repository
public interface WorkplaceRepoAsync extends Repository<Workplace, Long> {
    @Async
    public <S extends Workplace> S save(S workplaceE);
}

CodePudding user response:

You can try with the following code to have both methods available:

@Repository
public interface WorkplaceRepo extends JpaRepository<Workplace, Long> {
      @Async
      default <S extends Workplace> S saveAsync(S workplaceE) {
         return this.save(workplaceE);
      }
} 

This way the inherited not async method save(S entity) from JpaRepository would still be available to be called from your WorkplaceRepo.

  • Related