J2EE Programming/EJB-QL

From Wikibooks, open books for an open world
< J2EE Programming
Jump to: navigation, search

EJB Query Language is used to define what a finder method of an Entity bean should return. The EJB 1.1 specification offered no way to query entity beans. It resulted in different query languages for different application servers. When Sun published the EJB 2.0 specification it added a query language to find entity beans more easily.

Contents

[edit] Basic Syntax

SELECT_CLAUSE FROM_CLAUSE [WHERE_CLAUSE]

Both SELECT_CLAUSE and FROM_CLAUSE must be used but WHERE_CLAUSE is optional.

[edit] Finder methods

Finder methods are used to return a single or multiple Entities from the storage. The finder method is defined in entity's home interface. The return value of a finder is the beans remote interface or a collection of entity beans implementing the remote interface which were found.

[edit] Basic finder method

The simplest possible EJB-Query would be one which return all Entities in a given table.

@ejb.finder
  signature="Collection findAll()"
  query="SELECT DISTINCT OBJECT(p) FROM Player p"

As you can see, the EJB-Query looks nearly the same as a standard SQL query. The only difference is the terminal object(o) which is equivalent to: take all columns of a given row and transform the result into an entity bean instance.

[edit] Finder method with WHERE clause

Look at the example above. It differes from the finder method above only that a conditional for the players which should be returned is added.

@ejb.finder
  signature="Collection findByPosition(java.lang.String position)"
  query="SELECT DISTINCT OBJECT(p) FROM Player p WHERE p.position = ?1"

This finder method return all Players which play at the position which is entered by paramter one. If you have more than one paramter you can use them in your query with ?2, ?3 and so on.

[edit] Finder method which operates on relation

EJB Query differs from SQL esspecially if you want to use different relational tables.

@ejb.finder
   signature="Collection findByCity(java.lang.String city)"
   query="SELECT DISTINCT OBJECT(p) FROM Player p, IN (p.teams) AS t WHERE t.city = ?1"

This query return all players whose team plays in the city given with paramter one. With other word: return all Players who play in the team which is situated in a given city.

[edit] Select methods

In opposite to finder methods select methods might return a persistence field or other entity beans. So its possible to define a select method which returns a primitive data type instead of a complete object.

[edit] Example

Personal tools
Namespaces
Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export