Issue
There is native query written by developer
String sql = "Select * from TERP_META where id=" + id + " and type='KCH' ORDER BY ID ASC";
return entityManagerMaster.createNativeQuery(sql, TerpStatus.class).getResultList();
We can also write Named query for thist.
Now for simple query shall we use Native or Named? I understand that Native shall be used for complex queries and for simple Named is used but don't know the reason.
Can anyone clarify what is technically difference in execution of both to choose best among both?
Solution
It is not a named vs native at all, as you can have named native queries. Native are SQL queries, while non-native, in JPA world, refer to using JPQL - a different query language based off of your java entities. Which you choose depends on your application requirements, as generally more DB specific functionality can only be accessed through DB specific (native) SQL.
I personally don't like having to search through SQL queries to find them all over the application code and figure out problems when changing the model in ways that affects the schema - using JPQL lets JPA validate queries against the model upfront instead of having to execute the SQL queries against a DB. And the developers I have worked with don't always understand or work with the SQL tables, so JPQL is a bit closer to the data in the format (java objects) they work with. It also reduces problems/risks with people using string concat to build SQL queries, and using some customer defined value in that query string - a common vector for SQL injection attacks.
Answered By - Chris
Answer Checked By - Willingham (JavaFixing Volunteer)