Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create spring repository without entity

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?

like image 658
dramcio Avatar asked Apr 04 '19 10:04

dramcio


People also ask

Is @repository mandatory in spring boot?

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.

Does every entity need a repository?

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)...


2 Answers

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();     } } 
like image 52
Maciej Kowalski Avatar answered Sep 23 '22 08:09

Maciej Kowalski


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> { } 
like image 27
gagarwa Avatar answered Sep 22 '22 08:09

gagarwa