2

As mentioned in the documentation, JpaRepository lets us write native SQL queries. So, I wrote 2 different versions of the same query.

Version 1:

@Query(value = "SELECT b FROM branch AS b where b.companyId = ?1")
List<Branch> findByCompanyId(Long companyId);

Version 2:

@Query(nativeQuery = true, value = "SELECT * FROM branch where b.company_id = ?1")
List<Branch> findByCompanyId(Long companyId);

Both versions output the same results, I would like to know if there is a performance difference between these methods? Which method is recommended? What is the best practice?

  • Well, in that case the `@Query` is not even necessary, Spring Data will infer the same SQL query from that method (and I would default to that). The performance should be similar in most cases if the query is equivalent. I don't think there is a definitive best practice when providing your own queries; native queries are there for cases when you need some vendor-specific DB utility, I'd mostly use the non-native version just because that way you don't have to remember or check the mappings between DB columns and attributes in your entity – SrThompson Aug 19 '19 at 14:16
  • Agree with https://stackoverflow.com/users/8129075/srthompson and NEVER use * on a query. If a field were added, this query breaks your application. Is better to write all fields of a table – Jaume Morón i Tarrasa Aug 19 '19 at 14:18
  • thanks for the replies. –  Aug 19 '19 at 15:51

1 Answers1

1

If I had to guess I'd bet on the native query since the JPQL query (and the derived query) have to get translated into a native query. So there is an additional step.

But if that is true in your environment can only an experiment in your environment decide.

It is also rather likely irrelevant compared to the performance of actually executing the query and transforming the result.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348