[ Team LiB ] |
8.4 SearchesSearching with both persistence systems looks similar to JDO. They both use object-based query languages and leverage a similar API set. 8.4.1 Castor SearchesCastor uses the Object Query Language (OQL). OQL queries are similar to standard ANSI SQL but use object names in place of column fields. Example 8-7 details the implementation of a book search with Castor. Example 8-7. Searching for a book by title with Castorpublic Book findBookByTitle(String title) throws Exception { JDO jdo = new JDO("alternativepersistencedb"); jdo.loadConfiguration("database.xml"); Database db = jdo.getDatabase( ); db.begin( ); OQLQuery query = db.getOQLQuery("SELECT b FROM book.Book b WHERE title=$1"); query.bind("Alternative Persistence Systems"); QueryResults results = query.execute( ); // assume the first book found is the desired book Book book = (Book) results.next( ); db.commit( ); db.close( ); return book; } As before, all configuration information needs to be loaded and ready before any database operations can be performed. Once the connection has been established, the OQLQuery and QueryResults classes are used for searching. The most important line here is the getOQLQuery( ) method. This particular search looks for all entities that have a title value equal to the title attribute supplied by the calling method. If no results exist when next( ) is called, a NoSuchElementException will be thrown. 8.4.2 Hibernate SearchesSearching with Hibernate is almost identical to that with Castor. Example 8-8 details the implementation of searching with Hibernate. Example 8-8. Searching for a book by title with Hibernatepublic Book findBookByTitle(String title) throws Exception { Datastore ds = Hibernate.createDatastore( ); ds.storeFile("hibernate.xml"); SessionFactory sessionFactory = ds.buildSessionFactory( ); Session session = sessionFactory.openSession( ); Book book = null; List results = session.find("from o in class book.Book where title = ?", title, Hibernate.STRING); if (results.isEmpty( )) { throw new Exception ("Entity not found: " + title); } else { book = results.get(0); } session.close( ); return book; } The difference with Hibernate is that rather than throwing an exception when no entities are found, the framework supplies the method isEmpty( ) to determine if your search yielded no results. |
[ Team LiB ] |