Reputation: 52516
I have query (always return List has 1 SysAutoId
)
@Query(value = "SELECT * FROM SYSAutoID WHERE RefTypeCategory = ?1 AND BranchID = ?2 ", nativeQuery = true)
List<SysAutoId> findSpecific(Integer refTypeCategory, Integer branchId);
I want create a method like
@Query(value = "SELECT * FROM SYSAutoID WHERE RefTypeCategory = ?1 AND BranchID = ?2 ", nativeQuery = true)
SysAutoId findSpecific(Integer refTypeCategory, Integer branchId);
return one entity, how to do that?
Upvotes: 2
Views: 1385
Reputation: 66
You don't need Optional, you just need to make sure the query never returns more than 1 result, otherwise it will exception with IncorrectResultSizeDataAccessException.
You can see the supported query return types here
For a return type of T it says:
A unique entity. Expects the query method to return one result at most. If no result is found, null is returned. More than one result triggers an IncorrectResultSizeDataAccessException.
If you know your query will never return more than 1 result you should be fine, but if you're not sure I'd recommend adding LIMIT 1 to the end of your query.
Upvotes: 0
Reputation: 40058
The return type should be Optional
of Entity because it only returns the first matching record, look at the syntax of findById method
Optional<T> findById(ID primaryKey)
Code
@Query(value = "SELECT * FROM SYSAutoID WHERE RefTypeCategory = ?1 AND BranchID = ?2 ", nativeQuery = true)
Optional<SysAutoId> findSpecific(Integer refTypeCategory, Integer branchId);
Upvotes: 5