JHU Object-Oriented Software Engineering Course Homepage
Persistence
Table of Contents

Further Reading


13. Data Retrieval

The previous section shows how to persist objects to the database. This is not terribly useful unless those same objects can be retrieved. The Hibernate session obtained in the SessionFactory is useful for this as well. We may modify our GuessRepositoryImpl class to include the following method:

@SuppressWarnings("unchecked") public List<Guess> getAll() { List<Guess> allGuesses = this.sessionFactory.getCurrentSession().createQuery("from Guess").list(); return allGuesses; }

A corresponding method must be introduced to the GuessRepository interface for it to be callable by other beans, such as the GuessService.

The query above ("from Guess") is a very simple HQL query. The HQL (Hibernate query language) is an object-oriented query language which is based on the declarative approach of SQL but permits for queries in a fashion more compatible with the concepts inherent in Hibernate. More about HQL can be learned here.

Unfortunately, the @SuppressWarnings on the above code is necessary. Java is unable to ensure that Hibernate is returning a list which specifically contains Guess objects; indeed, the query could be structured so that it might not. In this case, though, we know that the list will contain only guess objects and that this cast is safe. Next, add the header for getAll() to the GuessRepository interface.

At this point, it should be clear how that method can be called by the GuessServiceImpl class. A method could be added to the GuessService interface to return that same list, allowing the TestBackingBean access to it; this, in turn, could render all of the guesses on a page. The actual implementation of this routine is left as an exercise to the reader.


Persistence
Table of Contents

Further Reading

Written by Zachary Palmer with help from Varun Sharma. Corrections and suggestions are welcome; please e-mail zachary dot palmer xX att Xx jhu.edu