Skip to content

Instantly share code, notes, and snippets.

@dungdm93
Created August 28, 2015 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dungdm93/7f990d8886b8b9d419ed to your computer and use it in GitHub Desktop.
Save dungdm93/7f990d8886b8b9d419ed to your computer and use it in GitHub Desktop.
[Java] [JPA] [JPQL] Parameters example
// JPA defines named parameters, and positional parameters.
// Named parameters can be specified in JPQL using the syntax :<name>.
Query query = em.createQuery("SELECT e FROM Employee e WHERE e.firstName = :first and e.lastName = :last");
query.setParameter("first", "Bob");
query.setParameter("last", "Smith");
List<Employee> list = query.getResultList();
// Positional parameters can be specified in JPQL using the syntax ? or ?<position>.
// Positional parameters start at position 1 not 0.
Query query = em.createQuery("SELECT e FROM Employee e WHERE e.firstName = ? and e.lastName = ?");
query.setParameter(1, "Bob");
query.setParameter(2, "Smith");
List<Employee> list = query.getResultList();
// --or--
Query query = em.createQuery("SELECT e FROM Employee e WHERE e.firstName = ?2 and e.lastName = ?1");
query.setParameter(2, "Bob");
query.setParameter(1, "Smith");
List<Employee> list = query.getResultList();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment