I want to create a Spring Data repository that is primarily there to collect complex queries both native and JPQL using @Query
. But I want to avoid tying it to an entity since it doesn't need to be tied to a specific entity.
@Repository
public interface UsageReports {
@Query(
nativeQuery = true,...
)
...
}
The solution in Is there a way to use a repository without applying repository base class? works but it doesn't support @Query
annotation.
The other way I did was to put an existing entity and note in the documentation to not use the find
methods that come with the extended methods.
/**
* <b>note do not use the JPA repository methods
*/
@Repository
public interface UsageReports extends JpaRepository<SomeEntity, Long> {
@Query(
nativeQuery = true,...
)
...
}
If you want to use the spring data @Query
annotation, you still have to extend some spring data interface, but instead of JpaRepository
interface you can extend Repository
interface:
package org.springframework.data.repository;
public interface Repository<T, ID> {
}
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
public interface CommonRepository extends Repository<FirstEntity, Object> {
@Query("select e from FirstEntity e where e.id=:id")
FirstEntity findFirstEntity(Long id);
@Query("select e from SecondEntity e where e.id=:id")
SecondEntity findSecondEntity(Long id);
}
This solution effectively hides all JpaRepository
methods because the Repository
interface does not contain any methods. However, the first generic parameter must still be an entity class, otherwise, an exception will occur by loading application context.