Finding entities in Active Objects is done through the
Finding all entities
The simplest one will return all entities of a given type. This is as simple as:
Here all the posts are going to be returned. Note that by default Active Object is lazy and therefore only IDs of the posts are going to be loaded. However it might still not be wise to load all the entities of a given type at once.
Finding entities with a given criteria
Adding a criteria is as simple as writing a SQL where clause. Here is what we would write to get the posts published between two dates:
Note how we made used of the
? placeholder just as when using JDBC's prepared statements. It is preferable to appending strings directly which might make the code prone to SQL injection.
We've made used of the
Query object here, but
EntityManager provides a shortcut that allows us to write that same query like this:
Finding entities with like
Adding a wildcard is also much like a SQL Query, here is what we would write to get a (contrived) field that is like the argument:
Ordering elements returned
The order of returned element is not guaranteed by default in SQL, so here is how to apply the order clause when using Active Objects:
Limiting the number of elements returned, and paging
There is also the possibility to limit the number of entities returned:
This query also starts selecting the elements from the 9th in the given order (which is not specified here). It is a good idea to specify a given order when using
limit for paging.