Loading objects by queries
Often we are interested in a (sub)set of results. We populate
our database with additional
hibintro.v1.model.User
instances:
package hibintro.v1.run;
...
public class PersistUsers {
...
final Transaction transaction = session.beginTransaction();
final User users[] = {new User("wings", "Fred Wings"),
new User("eve", "Eve Briggs")} ;
for (final User u : users ) {session.save(u);}
transaction.commit(); ...
Now we'd like to retrieve these objects. Hibernate offers the
Hibernate Query Language
(HQL) for object queries. As we will see HQL extends SQL
with respect to polymorphic queries. The current example does not use
inheritance leaving us with a simple HQL query
❶ in
hibintro.v1.run.RetrieveAll
:
hibintro.v1.model.User
instances by HQL. package hibintro.v1.run;
...
public class RetrieveAll {
...
final Query searchUsers = session.createQuery("from User");❶
final List<User> users = (List<User>) searchUsers.list();
for (final User u: users) {
System.out.println("uid=" + u.getUid() + ", " + u.getCname());
}
Being used to SQLwe notice the absence of
a SELECT clause in ❶: The ratio behind is
having a focus on objects rather than on attribute sets. Thus our
HQL query returns a set of
hibintro.v1.model.User
instances:
uid=eve, Eve Briggs uid=goik, Martin Goik uid=wings, Fred Wings
No. 17
HQL and SQL, analyzing results.
Q: |
We may actually retrieve attributes rather than objects. For this purpose our query actually resembles standard SQL ❶:
Use the |
A: |
A possible implementation reads:
Actually the two lines ❶ and ❷ are only needed during the development process to discover the result set's object structure. |
The careful reader may already expect HQL
to offer additional features namely predicate based queries. Following
hibintro.v1.run.SelectUser
we may restrict our
result set by an SQL style WHERE
clause:
final List<User> users = (List<User>) session.createQuery(
"from User u where u.cname like '%e%'").list();
for (final User u: users) {
System.out.println("Found user '" + u.getCname() + "'");
}
This time we receive a true subset of
hibintro.v1.model.User
instances:
Found user 'Eve Briggs' Found user 'Fred Wings'