In the previous trail, we mentioned that the drop down lists in the investment calculator application are populated with available funds and investors in the database, including their names and primary IDs. At the bottom of the calculator program, there is also a list of past calculation records from the database. We did not discuss how we get those data from the database.
In fact, retrieving all the rows in a table is very easy to do using the EJB QL. The following code snippet shows how to retrieve all funds from the Fund
table. It is very easy to understand if you know SQL. The EntityManager.createQuery()
creates a query with an EJB QL statement. The listResults()
method returns a collection of entity beans that are matched by the query.
@Stateless
public class QueryCalculator implements Calculator {
@PersistenceContext
protected EntityManager em;
public Collection <Fund> getFunds () {
return em.createQuery("from Fund f").getResultList();
}
// ... ...
}
The following snippet shows how to retrieve a complete list of rows in the TimedRecord
table. The results are returned with the latest records at the beginning of the list.
@Stateless
public class QueryCalculator implements Calculator {
@PersistenceContext
protected EntityManager em;
// ... ...
public Collection <TimedRecord> getRecords () {
return em.createQuery(
"select r from TimedRecord r order by r.ts desc").getResultList();
}
// ... ...
}
To see the above code in action, click on the button below to try out the sample application from the last trail.