How to add custom methods in all spring data services

Asked

Viewed 300 times

0

I implemented methods into one Repository for all my children repositories have the same methods. Download the code of how I implemented a Repository Personalized

This is the interface:

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

     List<T> findCustomNativeQuery(String sqlQuery);
 }

This is the implementation of the class:

 public class BaseMyRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements BaseMyRepository<T, ID>{

     private final EntityManager entityManager;

     public BaseMyRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager){
         super(entityInformation, entityManager);
         this.entityManager = entityManager;
     }

     @Transactional
     @Override
     public List<T> findCustomNativeQuery(String sqlQuery) {
         List<T> lista = entityManager.createNativeQuery(sqlQuery, this.getDomainClass()).getResultList();

         return lista;
     }


 }

This is my repository (Repository):

 public interface MyRepository extends BaseMyRepository<SmaempreEntity, Integer>{

 }

Now I need to know if it is possible to do the code below. Below I have exemplified what I need.

 @Service
 @Transactional
 public class MyBaseService<R extends BaseMyRepository, E> {

     @Autowired
     private R;

     public List<E> findAll() {
         return R.findAll();
     }

    public List<E> findCustomNativeQuery(String sqlQuery) {
         return R.findCustomNativeQuery(sqlQuery);
     }
 }


 public class MyService extends MyBaseService<MyRepository, MyEntity> {


 }

2 answers

0

Just looking at it like that is kind of complicated, but I believe it would work.

Did you try to run the project and made a mistake? If yes, put here the error that we can help you better.

0


I managed to run the class according to what I needed above. Below goes the code and used to run.

 public class BaseMyService<R extends BaseMyRepository, E> {

     public String COLUMNS_RESUME = null;

     @Autowired
     private final R baseMyRepository;

     public BaseMyService(R myRepository) {
         this.baseMyRepository = myRepository;
     }


     public List<E> findAll() {
         return baseMyRepository.findAll();
     }

     public List<E> findCustomNativeQuery(String sqlQuery) {

         return baseMyRepository.findCustomNativeQuery(sqlQuery);
     }
 }


 @Service
 @Transactional
 public class MyService extends BaseMyService<MyRepository, MyEntity>{


     public MyService(MyRepository myRepository) {
         super(myRepository);
     }
 }

This way I was able to customize a class of services where I can extend it and use the same methods in all services.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.