konstantin_doncov
konstantin_doncov

Reputation: 2879

Use @Query annotation not in the JpaRepository

I have the User entity in the database and it's JPA entity. I also have the UserDescription class which hasn't table in the database. I want to instantiate UserDescription class using different tables and entities. But I don't want to use EntityManager for it. So I found SELECT new ... pattern which can be used in @Query annotation, it's the perfect solution.

But I have simple issue - I need to annotate some method declaration which should be in interface. Usually it's done in JpaRepository, but UserDescription - isn't entity, so I can't do this!

Also, I tried to create POJO interface(UserDescriptionService) with method declaration which annotated using @Query annotation, tried to create field with this interface in the controller(), and annotated it with Autowired and of course got:

Field userDescriptionService in UserController required a bean of type 'UserDescriptionService' that could not be found.

So, how can I use @Query annotation not in the JpaRepository or how can I get JpaRepository for the non-entity class?

Upvotes: 0

Views: 1070

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36223

As M. Deinum already mentioned. You are not forced to return only Entities in JpaRepositories.

You can use the Constructor Expression (aka select new) or also projections. Find more about projections here:

https://docs.spring.io/spring-data/jpa/docs/2.0.9.RELEASE/reference/html/#projections

Upvotes: 1

Related Questions