02introtojpql
TRANSCRIPT
JPQ 2.0: JPQLQueries in JPQL
1
CEC
S 42
3 Le
ctur
e on
JPQ
L by
Dr.
Alv
aro
Mon
ge
JPQLThe EntityManager API allows us to manipulate entities by persisting, removing, updating themWhat about queries to find information from entities?
EM allows us to find an entity by ID.... but this is very limiting!
JPQLJava Persistence Query LanguageAllows retrieval of entities by general criteriaSyntax similar to SQL... but it is object-oriented!
The results obtained from SQL are in the form of rows and columns (tables), whereas JPQL uses an entity or a collection of entities.
JPQL is mapped to SQL and JDBC calls
2
CEC
S 42
3 Le
ctur
e on
JPQ
L by
Dr.
Alv
aro
Mon
ge
JPQL syntaxQueries:
SELECT <select expression>FROM <from clause>[WHERE <conditional expression>][ORDER BY <order by clause>][GROUP BY <group by clause>][HAVING <having clause>]
Removing entitiesDELETE FROM <entity name> [[AS] <identification variable>][WHERE <conditional expression>]
Updating entitiesUPDATE <entity name> [[AS] <identification variable>]SET <update statement> {, <update statement>}*[WHERE <conditional expression>]
3
CEC
S 42
3 Le
ctur
e on
JPQ
L by
Dr.
Alv
aro
Mon
ge
Queries: SELECT
Basic queries are specified as you would in SQLSELECT t FROM Team tSELECT t.teamName FROM Team t WHERE t.league='National'
Navigation expressions can be chained together to traverse complex entity graphsSELECT p FROM Player p WHERE p.team.teamName='Red Sox'SELECT t.players.firstName FROM Team t
4
CEC
S 42
3 Le
ctur
e on
JPQ
L by
Dr.
Alv
aro
Mon
geJPQL and JPA 2.0 AppsDynamic
JPQL query string dynamically specified at runtimeMore flexible than named queries since the JPQL statement is built dynamically and can vary depending on run-time conditions
Named queriesNamed queries are statically via metadata and are unchangeablePreferred over dynamic queries since parsing and translation is done when the application starts rather than every time the query is executed.
Native queriesUseful in executing a native SQL statement (instead of JPQL)
Criteria APIIntroduced in JPA 2.0
5
CEC
S 42
3 Le
ctur
e on
JPQ
L by
Dr.
Alv
aro
Mon
ge
Query APIOnce you create a Query object, you can use the Query API to work with it
getResultList(), getSingleResult(), executeUpdate()setParameter(), getNamedParameters()etc...
Examples:Query query = em.createQuery("SELECT p FROM Player p");List<Player> players = query.getResultList();
jpqlQuery = "SELECT p FROM Player p";if (someCriteria) jpqlQuery += " where p.teamName = :playerTeamName";query = em.createQuery(jpqlQuery);query.setParameter("playerTeamName", "Los Angeles Dodgers");List<Player> players = query.getResultList();
6
CEC
S 42
3 Le
ctur
e on
JPQ
L by
Dr.
Alv
aro
Mon
ge
Named QueriesFirst, annotate the Entity with NamedQuery:@Entity@NamedQuery(name=Player.FIND_PLAYERS_OF_NAMED_TEAM, query="select p from Player p where p.team.teamName = :teamName")public class Player implements Serializable { public static final String FIND_PLAYERS_OF_NAMED_TEAM = "Player.findPlayersOfNamedTeam";/* etc...*/
Then, use the query name to create a Query:Query q = em.createNamedQuery(Player.FIND_PLAYERS_OF_NAMED_TEAM);String aTeamName = "Los Angeles Dodgers";q.setParameter("teamName", aTeamName);List<Player> playerList = q.getResultList();
Notesname of the query is scoped to the persistence unit and must be unique within that scope
7
CEC
S 42
3 Le
ctur
e on
JPQ
L by
Dr.
Alv
aro
Mon
ge
Other JPQL queries
Retrieving list of Strings rather than entities:List<String> playerName = (String)em.createQuery ("SELECT p.firstName FROM Player p WHERE p.team.teamName='Boston Red Sox'" ).getResultList();
JPQL JoinsUnlike in SQL join queries, the select list of a JPQL join query typically includes a single entity or even a single entity fieldOnce you obtain an entity instance, you can then navigate to its related instances using corresponding getter methods.Joins are needed when you aggregate data...
8
CEC
S 42
3 Le
ctur
e on
JPQ
L by
Dr.
Alv
aro
Mon
geUse of JPQL joins
Aggregating values and use of JOINFind the size of each team’s roster.SQL?JPQL?SELECT t.teamName, COUNT(p.id)FROM Team t LEFT OUTER JOIN t.players p GROUP BY t.teamName
9
CEC
S 42
3 Le
ctur
e on
JPQ
L by
Dr.
Alv
aro
Mon
ge
JPQL and EntityManager
Retrieved entities are automatically managedWhether you use em.find() or JPQL or SQLThey are automatically attached to the current persistence context
10