41

Can anyone please explain me the differences between following methods of JPA's EntityManager:

  • createQuery()
  • createNamedQuery()
  • createNativeQuery()

And also explain to me in which cases we should use which method?

Andrzej Sydor
  • 1,373
  • 4
  • 13
  • 28
Krish
  • 1,804
  • 7
  • 37
  • 65

3 Answers3

68
  • The createQuery method is used to create dynamic queries, which are queries defined directly within an application’s business logic. Example:

    public List findWithName(String name) {
    return em.createQuery(
    "SELECT c FROM Customer c WHERE c.name LIKE :custName")
    .setParameter("custName", name)
    .setMaxResults(10)
    .getResultList();
    }
    
  • The createNamedQuery method is used to create static queries, or queries that are defined in metadata by using the javax.persistence.NamedQuery annotation. The name element of @NamedQuery specifies the name of the query that will be used with the createNamedQuery method. The query element of @NamedQuery is the query:

    @NamedQuery(
    name="findAllCustomersWithName",
    query="SELECT c FROM Customer c WHERE c.name LIKE :custName"
    )
    

Here’s an example of createNamedQuery, which uses the @NamedQuery:

    @PersistenceContext
    public EntityManager em;
    ...
    customers = em.createNamedQuery("findAllCustomersWithName")
    .setParameter("custName", "Smith")
    .getResultList();
  • The createNativeQuery Create an instance of Query for executing a native SQL statement. here are some reasons to choice createNativeQuery:

    • Low level access, which means that you can optimize and handle the mapping by yourself; with SQL you actually access the database table while with JPQL you access the entity objects;
    • Maybe you do not want to learn JPQL if you already know SQL
    • You already have the queries written in SQL, and do not have resources/time to port them to JPQL

For more details visit those links:

Creating Queries Using the Java Persistence Query Language

JPA why use createNamedQuery

Why do we need to create native query?

Community
  • 1
  • 1
Mourad BENKDOUR
  • 879
  • 2
  • 9
  • 11
  • Whilst this links may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the links for reference. Otherwise a comment would be enough. – Tobias Liefke Nov 19 '15 at 21:40
28
  1. CreateQuery: Used to create an JPQL
  2. createNamedQuery: Used to define queries with name in mapping file or annotation go to this
  3. createNativeQuery: Used to execute native/pure SQL queries Example
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
2

CreateQuery is used to create an JPQLqueries

createNamedQuery is used to define queries with name in mapping file or annotation, example: obj.createNamedQuery("entity.findbycode",Something.class)

createNativeQuery is used to execute native/pure SQL queries.

pirs
  • 2,410
  • 2
  • 18
  • 25