JPA/Hibernate: Named Query vs Native Query | Which one to use?

5.5k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

Great answer by @Chris already. I am just putting my view here

NamedQuery: NamedQuery are validated during compile time and hence they are validated already. So they are less prone to exceptions at runtime. In my point of view, using NamedQuery for very commonly executed methods is better.

Native query: They are written same as you would write your queries in your database clients like Sqlyog. Prefer writing them only when having complex and long queries. As @Chris says "a common vector for SQL injection attacks".