SlideShare a Scribd company logo
1 of 2
Download to read offline
EJBQL 3.0 Quick Reference Guide                            Parameters                                                   Optimizations
                                                           Parameters can be specified in query strings by placing a    Limiting/paging query results:
                                                           colon in front of the identifier. (i.e. :param)              Return a subset of the results, here, items 10 through 30.
                                                                                                                        Query q = em.createQuery(...);
                                                           Simple parameters:                                           q.setMaxResults(20);
                                                           Find all people named “John”. Parameters allow using         q.setFirstResult(10);
                                                           known data in the query, in this case a String.
                                                           Query q = em.createQuery(“select p from “                    Flush mode:
                                                             + “Person p where p.firstName=:param”);                    Set flushes to occur at commit or before query execution. If
                                                           q.setParameter(“param”, “John”);                             the flush mode is set to FlushModeType.COMMIT, changes
                                                           List<Person> people = (List<Person>)                         made during the transaction might not be visible in the
                                                             q.getResultList();                                         query execution results.
Query Structure                                                                                                         query.setFlushMode(FlushModeType.AUTO);
Query clauses must be in the specified order.              Bulk Update and Delete                                       query.setFlushMode(FlushModeType.COMMIT);
select [distinct] [new] <result>                           Performed for a single type of entity per statement.
from <identification-variable>                                                                                          Single Result
[[left | inner] join [fetch] <objects to join> ]           Update:                                                      Specify that only one result is expected and to return only
[where <filter>]                                           Replace nickname Johnny with name John.                      the single instance instead of a List.
[group by <grouping-clause> ]                              Query q = em.createQuery(“update Person p “                  Query q = em.createQuery(“select distinct p”
[having <filter>]                                            + “set p.firstName = ‘John’ where “                          + “ from Person p where p.firstName = “
                                                             + “p.firstName = ‘Johnny’”);                                 + “'UniqueName'“);
[order by <ordering-clause>]
                                                           int numUpdates = q.executeUpdate();                          Person john = (Person) q.getSingleResult();
update < identification-variable >
                                                           Delete:                                                      Aggregates, Projections, and Grouping
set < identification-variable.field = new_value >
                                                           Delete all those with no children. Delete does not cascade   Grouping allows aggregates and projections to be grouped
[where <filter>]                                           Query q = em.createQuery(“delete from “                      by a given field and optionally limited using “having”.
                                                             + “Person p where p.children is empty”);                   Available aggregates are min, max, sum, avg, and count.
delete from < identification-variable >                    int numDeleted = q.executeUpdate();
[where <filter>]
                                                                                                                        Simple grouping:
Query Examples                                             Subqueries                                                   select avg(p.age) from Person p
The following examples use this sample class and           Find the youngest people in the company.                       group by p.firstName
assume an EntityManager named “em”.                        select p from Person p where p.age =
@Entity(access=AccessType.FIELD)                             (select min(p.age) from Person p)                          Limiting grouping with “having” expression:
public class Person {
  @Id private int id;                                                                                                   Group by firstName where the firstName starts with “J”.
                                                           Find those whose last name is part of a street address.      select count(p) from Person p
  @Version private long version;                           select p from Person p where p.lastName in                     group by p.firstName
  private int age;                                           (select a.street from Address a)                             having lower(p.firstName) like ‘j%’
  private String firstName;
  private String lastName;
  @OneToOne private Address address;                       Ordering Results                                             EJBQL from JDO
  @OneToMany private Set<Person> children;                 Order query results by age, oldest first.                    Execute an EJBQL query via the JDO Query interface.
}                                                          select p from Person p order by p.age desc                   Query q = pm.newQuery(
Basic Example                                                                                                             kodo.query.QueryLanguages.LANG_EJBQL,
Query q = em.createQuery(“select p from “                  Order query results by name, from A to Z, and then by          “select p from Person p where ”
  + “Person p where p.firstName=’John’”);                  age, from oldest to youngest.                                    + “p.address.state = :stateCode”);
List<Person> people = (List<Person>)                       select p from Person p                                       List<Person> people = (List<Person>)
  q.getResultList();                                         order by p.firstName asc, p.age desc                         q.execute(“MA”);
for (Person person : people)
  log(person.getLastName());

                                                                             © 2005 SolarMetric, Inc.
                                             Content based upon EJB3.0 public draft http://solarmetric.com/resources/ejbql-quickref.pdf
EJBQL 3.0 Quick Reference Guide                           Where Clause Methods                                         Result Classes and Aliases
                                                          The following methods may be used as part of a query         You can have query results placed directly into a custom
                                                          where clause. For example, “where p.firstName like           class. This example uses the custom class Name below.
                                                          (‘%ohn%’)” or “where sqrt(p.age) > 6”.                       public class Name
                                                          General     is [not] null,                                   {
                                                                       [not] exists                                      private String first;
                                                          Collection   size(Collection)                                  private String last;
                                                                       member [of],                                      public Name(String f, String l) {
                                                                       [not] in                                            this.first = f;
                                                                       is [not] empty,                                     this.last = l;
                                                                       all | any | some                                  }
                                                          String       [not] like,                                       // ...
                                                                       concat(String, String),                         }
SQL Queries
                                                                       trim([leading | trailing |
Queries can use direct SQL.                                              both] <char to trim>                          Query q = em.createQuery(“select “
Find people whose first name is “John”.                                  [from] String)                                  + “new com.example.Name(p.firstName, “
Query sql = em.createNativeQuery(“SELECT”                              lower(String),                                    + “p.lastName) from Person p “
  + “ FIRST, LAST, AGE FROM PERSON”                                    upper(String),                                    + “where p.age > :param”);
  + “ WHERE FIRST = ‘JOHN’”,                                           length(String),                                 List<Name> names = (List<Name>)
  com.example.Person.class);                                           locate(String, String[, int                       q.setParameter(“param”, 30).
List<Person> people = (List<Person>)                                     startpoint]),                                   getResultList();
    sql.execute();                                                     substring(int, int)                             for(Name name : names)
                                                                       abs(numeric),                                     printLabel(name);
                                                          Math
Named Queries                                                          sqrt(numeric),
                                                                       mod(numeric, numeric)                           Joins
Query definition:                                         Date         [not] between
@NamedQuery(name=“minorsByFirstName”,                                                                                  Inner join:
  queryString=“select p from Person p                     Regular Expressions                                          Select all people named John that have children.
  where p.age < 18 group by                               The “like” expression accepts limited wildcard matching.     select p from Person p join p.children c
  p.firstName”)                                                                                                          where p.firstName = ‘John’
                                                          _     represents a single character
                                                                                                                       Use of the keyword ‘inner’ is optional
                                                          %     represents multiple characters
Use the named query in code:
List<Person> minors = (List<Person>)                      All people with ‘rick’ in their name – Patrick, Rick, etc.
                                                          select p from Person p                                       The prior query is equivalent to this EJB 2.1 query.
  em.createNamedQuery(                                                                                                 select object(p) from Person p,
                                                            where lower(p.firstName) like ‘%rick%’
  “minorsByFirstName”).getResultList();                                                                                  in(p.children) c where p.firstName=‘John’
                                                          Where Clause Operators
Keywords                                                  =         equal (note: can be used with Strings)
                                                                                                                       Left outer join:
Reserved keywords are not case sensitive.                 <>        not equal
                                                                                                                       Select the last name of every person and the age of each of
                                                          >         greater than
                                                                                                                       his/her children, if any.
select, from, where, update, delete,                      <         less than                                          select p.lastName, c.age from Person p
join, outer, inner, group, by, having,                    >=        greater than or equal                                left join p.children c
fetch, distinct, object, null, true,                      <=        less than or equal
false, not, and, or, between, like, in,                   AND       conditional AND                                    Fetch join:
as, unknown, empty, member, of, is, avg,                  OR        conditional OR
max, min, sum, count, order, by, asc,                                                                                  Select everyone named John and eagerly fetch information
                                                          -         subtract or convert sign                           about any children.
desc, mod, upper, lower, trim, position,
character_length, char_length,                            +         add                                                select distinct p from Person p
bit_length, current_time, current_date,                   *         multiply                                             left join fetch p.children
current_timestamp, new, left, exists,                     /         divide                                               where p.firstName=‘John’
all, any, some, size                                      NOT       logical complement

                                                                            © 2005 SolarMetric, Inc.
                                            Content based upon EJB3.0 public draft http://solarmetric.com/resources/ejbql-quickref.pdf

More Related Content

What's hot

Web programming in Haskell
Web programming in HaskellWeb programming in Haskell
Web programming in Haskellchriseidhof
 
The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202Mahmoud Samir Fayed
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring DataOliver Gierke
 
Spring Data for KSDG 2012/09
Spring Data for KSDG 2012/09Spring Data for KSDG 2012/09
Spring Data for KSDG 2012/09永昇 陳
 
More Stored Procedures and MUMPS for DivConq
More Stored Procedures and  MUMPS for DivConqMore Stored Procedures and  MUMPS for DivConq
More Stored Procedures and MUMPS for DivConqeTimeline, LLC
 
Implementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBImplementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBOren Eini
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objectsHusain Dalal
 
Erlang for data ops
Erlang for data opsErlang for data ops
Erlang for data opsmnacos
 
The Ring programming language version 1.5.1 book - Part 29 of 180
The Ring programming language version 1.5.1 book - Part 29 of 180The Ring programming language version 1.5.1 book - Part 29 of 180
The Ring programming language version 1.5.1 book - Part 29 of 180Mahmoud Samir Fayed
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinFabio Collini
 
The Ring programming language version 1.5.4 book - Part 31 of 185
The Ring programming language version 1.5.4 book - Part 31 of 185The Ring programming language version 1.5.4 book - Part 31 of 185
The Ring programming language version 1.5.4 book - Part 31 of 185Mahmoud Samir Fayed
 
OSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour HadoopOSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour HadoopPublicis Sapient Engineering
 
The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31Mahmoud Samir Fayed
 
The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212Mahmoud Samir Fayed
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFabio Collini
 
Scala Domain Modeling and Architecture
Scala Domain Modeling and ArchitectureScala Domain Modeling and Architecture
Scala Domain Modeling and ArchitectureHossam Karim
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFabio Collini
 

What's hot (20)

Web programming in Haskell
Web programming in HaskellWeb programming in Haskell
Web programming in Haskell
 
The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202The Ring programming language version 1.8 book - Part 36 of 202
The Ring programming language version 1.8 book - Part 36 of 202
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
Spring Data for KSDG 2012/09
Spring Data for KSDG 2012/09Spring Data for KSDG 2012/09
Spring Data for KSDG 2012/09
 
More Stored Procedures and MUMPS for DivConq
More Stored Procedures and  MUMPS for DivConqMore Stored Procedures and  MUMPS for DivConq
More Stored Procedures and MUMPS for DivConq
 
Clean code
Clean codeClean code
Clean code
 
Implementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBImplementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDB
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objects
 
Erlang for data ops
Erlang for data opsErlang for data ops
Erlang for data ops
 
The Ring programming language version 1.5.1 book - Part 29 of 180
The Ring programming language version 1.5.1 book - Part 29 of 180The Ring programming language version 1.5.1 book - Part 29 of 180
The Ring programming language version 1.5.1 book - Part 29 of 180
 
H base programming
H base programmingH base programming
H base programming
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
 
The Ring programming language version 1.5.4 book - Part 31 of 185
The Ring programming language version 1.5.4 book - Part 31 of 185The Ring programming language version 1.5.4 book - Part 31 of 185
The Ring programming language version 1.5.4 book - Part 31 of 185
 
OSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour HadoopOSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
 
The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31
 
The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
 
Scala Domain Modeling and Architecture
Scala Domain Modeling and ArchitectureScala Domain Modeling and Architecture
Scala Domain Modeling and Architecture
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 

Viewers also liked

Query browser-es
Query browser-esQuery browser-es
Query browser-esjaiverlh
 
Jsf tutorial
Jsf tutorialJsf tutorial
Jsf tutorialjaiverlh
 
Replicación maestro
Replicación maestroReplicación maestro
Replicación maestrojaiverlh
 
Introduccion my sql
Introduccion my sqlIntroduccion my sql
Introduccion my sqljaiverlh
 
Tema5 3.jsf
Tema5 3.jsfTema5 3.jsf
Tema5 3.jsfjaiverlh
 
El internet y sus principales componentes
El internet y sus principales componentesEl internet y sus principales componentes
El internet y sus principales componentesJavier Ramos
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerLuminary Labs
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsLinkedIn
 

Viewers also liked (8)

Query browser-es
Query browser-esQuery browser-es
Query browser-es
 
Jsf tutorial
Jsf tutorialJsf tutorial
Jsf tutorial
 
Replicación maestro
Replicación maestroReplicación maestro
Replicación maestro
 
Introduccion my sql
Introduccion my sqlIntroduccion my sql
Introduccion my sql
 
Tema5 3.jsf
Tema5 3.jsfTema5 3.jsf
Tema5 3.jsf
 
El internet y sus principales componentes
El internet y sus principales componentesEl internet y sus principales componentes
El internet y sus principales componentes
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving Cars
 

Similar to Software architecture2008 ejbql-quickref

Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Leonardo Soto
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Leonardo Soto
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012Timo Westkämper
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useSharon Rozinsky
 
Java Play Restful JPA
Java Play Restful JPAJava Play Restful JPA
Java Play Restful JPAFaren faren
 
define a class name Employee whose objects are records for employee..pdf
define a class name Employee whose objects are records for employee..pdfdefine a class name Employee whose objects are records for employee..pdf
define a class name Employee whose objects are records for employee..pdffashioncollection2
 
NetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience ReportNetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience ReportAnton Arhipov
 
Not sure why my program wont run.Programmer S.Villegas helper N.pdf
Not sure why my program wont run.Programmer S.Villegas helper N.pdfNot sure why my program wont run.Programmer S.Villegas helper N.pdf
Not sure why my program wont run.Programmer S.Villegas helper N.pdfwasemanivytreenrco51
 
How to ship customer value faster with step functions
How to ship customer value faster with step functionsHow to ship customer value faster with step functions
How to ship customer value faster with step functionsYan Cui
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackGaryCoady
 
GR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective GroovyGR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective GroovyGR8Conf
 
Student management system
Student management systemStudent management system
Student management systemgeetika goyal
 
Leveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better ValidationLeveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better ValidationTomer Gabel
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodecamp Romania
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesVMware Tanzu
 
Define a class named Doctor whose objects are records for clinic’s d.pdf
Define a class named Doctor whose objects are records for clinic’s d.pdfDefine a class named Doctor whose objects are records for clinic’s d.pdf
Define a class named Doctor whose objects are records for clinic’s d.pdfMALASADHNANI
 

Similar to Software architecture2008 ejbql-quickref (20)

Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)
 
Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
 
Java Play Restful JPA
Java Play Restful JPAJava Play Restful JPA
Java Play Restful JPA
 
define a class name Employee whose objects are records for employee..pdf
define a class name Employee whose objects are records for employee..pdfdefine a class name Employee whose objects are records for employee..pdf
define a class name Employee whose objects are records for employee..pdf
 
Grails queries
Grails   queriesGrails   queries
Grails queries
 
NetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience ReportNetBeans Plugin Development: JRebel Experience Report
NetBeans Plugin Development: JRebel Experience Report
 
JNI 使用淺談
JNI 使用淺談JNI 使用淺談
JNI 使用淺談
 
Not sure why my program wont run.Programmer S.Villegas helper N.pdf
Not sure why my program wont run.Programmer S.Villegas helper N.pdfNot sure why my program wont run.Programmer S.Villegas helper N.pdf
Not sure why my program wont run.Programmer S.Villegas helper N.pdf
 
How to ship customer value faster with step functions
How to ship customer value faster with step functionsHow to ship customer value faster with step functions
How to ship customer value faster with step functions
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
GR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective GroovyGR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective Groovy
 
Student management system
Student management systemStudent management system
Student management system
 
Leveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better ValidationLeveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better Validation
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
 
Java 8 Examples
Java 8 ExamplesJava 8 Examples
Java 8 Examples
 
Define a class named Doctor whose objects are records for clinic’s d.pdf
Define a class named Doctor whose objects are records for clinic’s d.pdfDefine a class named Doctor whose objects are records for clinic’s d.pdf
Define a class named Doctor whose objects are records for clinic’s d.pdf
 

Recently uploaded

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 

Recently uploaded (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 

Software architecture2008 ejbql-quickref

  • 1. EJBQL 3.0 Quick Reference Guide Parameters Optimizations Parameters can be specified in query strings by placing a Limiting/paging query results: colon in front of the identifier. (i.e. :param) Return a subset of the results, here, items 10 through 30. Query q = em.createQuery(...); Simple parameters: q.setMaxResults(20); Find all people named “John”. Parameters allow using q.setFirstResult(10); known data in the query, in this case a String. Query q = em.createQuery(“select p from “ Flush mode: + “Person p where p.firstName=:param”); Set flushes to occur at commit or before query execution. If q.setParameter(“param”, “John”); the flush mode is set to FlushModeType.COMMIT, changes List<Person> people = (List<Person>) made during the transaction might not be visible in the q.getResultList(); query execution results. Query Structure query.setFlushMode(FlushModeType.AUTO); Query clauses must be in the specified order. Bulk Update and Delete query.setFlushMode(FlushModeType.COMMIT); select [distinct] [new] <result> Performed for a single type of entity per statement. from <identification-variable> Single Result [[left | inner] join [fetch] <objects to join> ] Update: Specify that only one result is expected and to return only [where <filter>] Replace nickname Johnny with name John. the single instance instead of a List. [group by <grouping-clause> ] Query q = em.createQuery(“update Person p “ Query q = em.createQuery(“select distinct p” [having <filter>] + “set p.firstName = ‘John’ where “ + “ from Person p where p.firstName = “ + “p.firstName = ‘Johnny’”); + “'UniqueName'“); [order by <ordering-clause>] int numUpdates = q.executeUpdate(); Person john = (Person) q.getSingleResult(); update < identification-variable > Delete: Aggregates, Projections, and Grouping set < identification-variable.field = new_value > Delete all those with no children. Delete does not cascade Grouping allows aggregates and projections to be grouped [where <filter>] Query q = em.createQuery(“delete from “ by a given field and optionally limited using “having”. + “Person p where p.children is empty”); Available aggregates are min, max, sum, avg, and count. delete from < identification-variable > int numDeleted = q.executeUpdate(); [where <filter>] Simple grouping: Query Examples Subqueries select avg(p.age) from Person p The following examples use this sample class and Find the youngest people in the company. group by p.firstName assume an EntityManager named “em”. select p from Person p where p.age = @Entity(access=AccessType.FIELD) (select min(p.age) from Person p) Limiting grouping with “having” expression: public class Person { @Id private int id; Group by firstName where the firstName starts with “J”. Find those whose last name is part of a street address. select count(p) from Person p @Version private long version; select p from Person p where p.lastName in group by p.firstName private int age; (select a.street from Address a) having lower(p.firstName) like ‘j%’ private String firstName; private String lastName; @OneToOne private Address address; Ordering Results EJBQL from JDO @OneToMany private Set<Person> children; Order query results by age, oldest first. Execute an EJBQL query via the JDO Query interface. } select p from Person p order by p.age desc Query q = pm.newQuery( Basic Example kodo.query.QueryLanguages.LANG_EJBQL, Query q = em.createQuery(“select p from “ Order query results by name, from A to Z, and then by “select p from Person p where ” + “Person p where p.firstName=’John’”); age, from oldest to youngest. + “p.address.state = :stateCode”); List<Person> people = (List<Person>) select p from Person p List<Person> people = (List<Person>) q.getResultList(); order by p.firstName asc, p.age desc q.execute(“MA”); for (Person person : people) log(person.getLastName()); © 2005 SolarMetric, Inc. Content based upon EJB3.0 public draft http://solarmetric.com/resources/ejbql-quickref.pdf
  • 2. EJBQL 3.0 Quick Reference Guide Where Clause Methods Result Classes and Aliases The following methods may be used as part of a query You can have query results placed directly into a custom where clause. For example, “where p.firstName like class. This example uses the custom class Name below. (‘%ohn%’)” or “where sqrt(p.age) > 6”. public class Name General is [not] null, { [not] exists private String first; Collection size(Collection) private String last; member [of], public Name(String f, String l) { [not] in this.first = f; is [not] empty, this.last = l; all | any | some } String [not] like, // ... concat(String, String), } SQL Queries trim([leading | trailing | Queries can use direct SQL. both] <char to trim> Query q = em.createQuery(“select “ Find people whose first name is “John”. [from] String) + “new com.example.Name(p.firstName, “ Query sql = em.createNativeQuery(“SELECT” lower(String), + “p.lastName) from Person p “ + “ FIRST, LAST, AGE FROM PERSON” upper(String), + “where p.age > :param”); + “ WHERE FIRST = ‘JOHN’”, length(String), List<Name> names = (List<Name>) com.example.Person.class); locate(String, String[, int q.setParameter(“param”, 30). List<Person> people = (List<Person>) startpoint]), getResultList(); sql.execute(); substring(int, int) for(Name name : names) abs(numeric), printLabel(name); Math Named Queries sqrt(numeric), mod(numeric, numeric) Joins Query definition: Date [not] between @NamedQuery(name=“minorsByFirstName”, Inner join: queryString=“select p from Person p Regular Expressions Select all people named John that have children. where p.age < 18 group by The “like” expression accepts limited wildcard matching. select p from Person p join p.children c p.firstName”) where p.firstName = ‘John’ _ represents a single character Use of the keyword ‘inner’ is optional % represents multiple characters Use the named query in code: List<Person> minors = (List<Person>) All people with ‘rick’ in their name – Patrick, Rick, etc. select p from Person p The prior query is equivalent to this EJB 2.1 query. em.createNamedQuery( select object(p) from Person p, where lower(p.firstName) like ‘%rick%’ “minorsByFirstName”).getResultList(); in(p.children) c where p.firstName=‘John’ Where Clause Operators Keywords = equal (note: can be used with Strings) Left outer join: Reserved keywords are not case sensitive. <> not equal Select the last name of every person and the age of each of > greater than his/her children, if any. select, from, where, update, delete, < less than select p.lastName, c.age from Person p join, outer, inner, group, by, having, >= greater than or equal left join p.children c fetch, distinct, object, null, true, <= less than or equal false, not, and, or, between, like, in, AND conditional AND Fetch join: as, unknown, empty, member, of, is, avg, OR conditional OR max, min, sum, count, order, by, asc, Select everyone named John and eagerly fetch information - subtract or convert sign about any children. desc, mod, upper, lower, trim, position, character_length, char_length, + add select distinct p from Person p bit_length, current_time, current_date, * multiply left join fetch p.children current_timestamp, new, left, exists, / divide where p.firstName=‘John’ all, any, some, size NOT logical complement © 2005 SolarMetric, Inc. Content based upon EJB3.0 public draft http://solarmetric.com/resources/ejbql-quickref.pdf