by BehindJava

What is the difference between query, native query, named query and typed query

Home » interview » What is the difference between query, native query, named query and typed query

Here is a quick tutorial on stating the differences between the query, native query, named query, and typed query.

There are three basic types of JPA Queries:

  • Query, written in Java Persistence Query Language (JPQL) syntax. There are two additional Query sub-types:

    • TypedQuery
    • NamedQuery
  • NativeQuery, written in plain SQL syntax
  • Criteria API Query, constructed programmatically via different methods

Query

Query refers to JPQL/HQL query with syntax similar to SQL generally used to execute DML statements(CRUD operations).

In JPA, you can create a query using entityManager.createQuery(). You can look into API for more detail.

In Hibernate, you use session.createQuery()“.

Example:

@Repository
public interface AccountCategoryRepository extends JpaRepository<AccountCategoryDTO, String> {
    
    // Spring JPA In cause using method name
    Optional<AccountCategoryDTO> findAccountCategory(String id);   

    // Spring JPA In cause using @Query
    @Query(value="select * from tbl_account_category acc where acc.account_category_id=?1")
	Optional<AccountCategoryDTO> findAccountCategory(String id);
    
    // Spring JPA In cause using native query
	@Query(value="select * from tbl_account_category acc where acc.account_category_id=?1", nativeQuery=true)
	Optional<AccountCategoryDTO> findAccountCategory(String id);

TypedQuery

TypedQuery gives you an option to mention the type of entity when you create a query and therefore any operation thereafter does not need an explicit cast to the intended type. Whereas the normal Query API does not return the exact type of Object you expect and you need to cast.

private static void findEmployees() {
      System.out.println("-- all Employees--");
      EntityManager em = entityManagerFactory.createEntityManager();
      TypedQuery<Employee> query = em.createQuery("SELECT e FROM Employee e", Employee.class);
      List<Employee> resultList = query.getResultList();
      resultList.forEach(System.out::println);
  }

NamedQuery

Similar to how the constant is defined. NamedQuery is the way you define your query by giving it a name. You can define this in mapping files of hibernate and also use annotations at the entity level.

Example:

@Entity
@Table(name = "cities")
@NamedQuery(name = "City.findAllOrderedDescending",
        query = "SELECT c FROM City c ORDER BY c.name DESC")
public class City { }

NativeQuery

Native query refers to actual SQL queries (referring to actual database objects). These queries are the SQL statements that can be directly executed in the database using a database client.

JPA : entityManager.createNativeQuery() Hibernate (Non-JPA implementation): session.createSQLQuery()