简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM