How to add custom methods to all spring data services

0

I've implemented methods on a Repository so all my child repositories have the same methods. Lowers the code of how I implemented a% custom%

This is the interface:

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

     List<T> findCustomNativeQuery(String sqlQuery);
 }

This is the class implementation:

 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's 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> {


 }
    
asked by anonymous 16.05.2017 / 23:43

2 answers

0

I was able to execute the class according to what I needed above. Below is the code and I used it to execute.

 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);
     }
 }

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

    
23.05.2017 / 00:24
0

Just looking at it is a bit complicated, but I think it would work.

Have you tried running the project and made a mistake? If so, post here the error that we can help you better.

    
22.05.2017 / 20:31