简体   繁体   中英

How Spring data jpa @Query annotation works

I am new to both Spring data and JPA . I am curious how the query annotation works. Like in my scenario I need all the userIds of an organization. So this is what i did:

 @Query("select o.userId from User o where o.orgId = :orgId")   
 List <Integer> findUserIdsByOrgId(@Param("orgId")int orgId);

The above statement works fine. I get a list of user Ids. The problem is when I alter the query to search for the User

 @Query("select o from User o where o.orgId = :orgId")  
 List <Integer> findUserIdsByOrgId(@Param("orgId")int orgId);

As I remove userId from o.userId the whole object is returned and not an Integer .

My assumption is that an error should be thrown if the return type is not matched to the one in the query.

The thing is that generics in Java are removed in runtime .

Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.

So Spring cannot make a check for generic type and trusts you that you don't mismatch type. Of course, if you return Integer instead of User (without generics) then Spring would throw an error.

将返回类型从List<Integer>更改为List<User> ,它应该可以正常工作。

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