Jump to content

Jakarta EE Programming/EJB-QL

25% developed
From Wikibooks, open books for an open world

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.

Basic Syntax

[edit | edit source]
SELECT_CLAUSE FROM_CLAUSE [WHERE_CLAUSE]

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

Finder methods

[edit | edit source]

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.

Basic finder method

[edit | edit source]

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, although it's not the name of the tables but the name of the EJB classes and it's not the name of the columns but the name of the EJB properties. 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.

Finder method with WHERE clause

[edit | edit source]

Look at the example above. It differs 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 returns all Players which play at the position which is entered by parameter one. If you have more than one parameter you can use them in your query with ?2, ?3 and so on.

Finder method which operates on relation

[edit | edit source]

EJB Query differs from SQL especially 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 parameter one. In other words: return all Players who play in the team which is situated in a given city.

Select methods

[edit | edit source]

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

Example

[edit | edit source]
Clipboard

To do:
Add examples.