I want to use spring data repository interface to execute native queries - I think this way is the simplest because of low complexity.
But when extending interface ex. CrudRepository<T, ID>
I need to write T - my entity, which is not available.
My native queries does not return any concrete entity, so what is the best way to create spring repository without entity?
It is indeed not necessary to put the @Repository annotation on interfaces that extend JpaRepository ; Spring recognizes the repositories by the fact that they extend one of the predefined Repository interfaces. From the javadoc: Annotation to enable JPA repositories.
It depends on your logic and how "important" are every entity. For example, if you had the entities User and Address you could have UserRepository and AddressRepository. But only UserService, with methods like addAddress(User user, Address address)...
CrudRepository
or JpaRepository
were not designed to work without an <Entity,ID>
pair.
You are better off creating a custom repo, inject EntityManager and query from there:
@Repository public class CustomNativeRepositoryImpl implements CustomNativeRepository { @Autowired private EntityManager entityManager; @Override public Object runNativeQuery() { entityManager.createNativeQuery("myNativeQuery") .getSingleResult(); } }
Currently there is no functionality in JPA to create repositories with only native or JPQL/HQL queries (using @Query notation). To get around this, you can create a dummy object to insert into the extension interface like below:
@Entity public class RootEntity { @Id private Integer id; } @Repository public interface Repository extends JpaRepository<RootEntity, Integer> { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With