2

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?

1
  • If you are using Sping Data JPA, you can get your queries autogenerted by Spring. See the Spring Data JPA documentation. Commented Jul 20, 2019 at 15:45

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.