Spring Data: Override save method

前端 未结 11 1257
温柔的废话
温柔的废话 2020-11-27 05:30

I\'m considering spring data for a project. Is it possible to override the per default generated save method? And if yes, how?

11条回答
  •  抹茶落季
    2020-11-27 05:39

    In order to properly override the save method, you have to create a interface with the proper signature of the original method declared on CrudRepository, including the generics

    public interface MyCustomRepository {
         S save(S entity);
    }
    

    Then, create your implementation ( the suffix Impl is important at the name of the class)

    public class MyCustomRepositoryImpl implements MyCustomRepository {
    
        @Autowired
        private EntityManager entityManager;
    
    
        @Override
        public  S save(S entity) {
           /**
             your custom implementation comes here ...
             i think the default one is just        
            return this.entityManager.persist(entity);
           */
        }
    
    }
    

    Finally, extend your repository with the previously created interface

    @RepositoryRestResource
    @Repository
    public interface MyBeanRepository extends PagingAndSortingRepository, MyCustomRepository {}
    

提交回复
热议问题