I solved it by creating a custom implementation of the repository, implementing a custom interface.
First I had to declare the interface:
public interface CustomQuery {
public List<Integer>myCustomQuery(int id)
}
Then I implemented it in my custom repository. The name is important, it has to begin with the name of the repository interface it is extending. My repo is named MediaRepository
so I named the custom implementation MediaRepositoryImpl
:
@Component
public class MediaRepositoryImpl implements CustomQuery {
@PersistenceContext
EntityManager manager;
public List<Integer>myCustomQuery(int id){
Query q = manager.createNativeQuery(SQL_QUERY_GOES_HERE);
List<Integer> ids = new ArratList<Integer>();
@SuppressWarnings("unchecked")
List<Integer> result = q.getResultList();
for(Integer o : result){
//process the results and add them to the list
}
return list;
}
}
This way, you can do custom native queries while still keeping the regular Repositories clean. This approach is also easier to test.