Search code examples
sqldatabasejpajpql

Is JPA "native SQL" independent of the underlying DBMS


When using JPA, one can either use JPQL or "native SQL" to write queries:

JPQL example:

interface TodoRepository extends Repository<Todo, Long> {

    @Query("SELECT t FROM Todo t WHERE t.title = 'title'")
    public List<Todo> findByTitle();
}

SQL example:

interface TodoRepository extends Repository<Todo, Long> {

    @Query(value = "SELECT * FROM todos t WHERE t.title = 'title'", 
    nativeQuery=true)
    public List<Todo> findByTitle();
}

JPQL is obviously independent of the underlying database (Oracle, MySQL, etc.) My question is: is the SQL also independent of the underlying database? That is, is this SQL some form of "neutral" SQL that then gets translated into a specific SQL dialect (such a MySQL-dialect)?


Solution

  • A JPA "native query" is SQL. And SQL varies from one RDBMS to another. You are totally database dependent when using "native queries". So you should always strive to use JPQL wherever possible.

    There is no vendor neutral form. Obviously if all RDBMS vendors stuck to plan ANSI SQL and supported the same syntax then all would be simple, but they don't, and it isn't