createTestBooks(s);
Transaction tx = s.beginTransaction();
QueryParser parser = new QueryParser("title", new StopAnalyzer() );
Query query = parser.parse( "summary:lucene" );
FullTextQuery hibQuery = s.createFullTextQuery( query, Book.class );
List<Book> result = hibQuery.list();
assertNotNull( result );
assertEquals( "Wrong number of test results.", 3, result.size() );
// make sure that the order is according to in which order the books got inserted
// into the index.
int id = 1;
for(Book b : result) {
assertEquals( "Expected another id", Integer.valueOf( id ), b.getId() );
id++;
}
// now the same query, but with a lucene sort specified.
query = parser.parse( "summary:lucene" );
hibQuery = s.createFullTextQuery( query, Book.class );
Sort sort = new Sort(new SortField("id", true));
hibQuery.setSort(sort);
result = hibQuery.list();
assertNotNull( result );
assertEquals( "Wrong number of test results.", 3, result.size() );
id = 3;
for(Book b : result) {
assertEquals("Expected another id", Integer.valueOf( id ), b.getId());
id--;
}
// order by summary
query = parser.parse( "summary:lucene OR summary:action" );
hibQuery = s.createFullTextQuery( query, Book.class );
sort = new Sort( new SortField( "summary_forSort", false ) ); //ASC
hibQuery.setSort( sort );
result = hibQuery.list();
assertNotNull( result );
assertEquals( "Wrong number of test results.", 4, result.size() );
assertEquals( "Groovy in Action", result.get( 0 ).getSummary() );
// order by summary backwards
query = parser.parse( "summary:lucene OR summary:action" );
hibQuery = s.createFullTextQuery( query, Book.class );
sort = new Sort( new SortField( "summary_forSort", true ) ); //DESC
hibQuery.setSort( sort );
result = hibQuery.list();
assertNotNull( result );
assertEquals( "Wrong number of test results.", 4, result.size() );
assertEquals( "Hibernate & Lucene", result.get( 0 ).getSummary() );
// order by date backwards
query = parser.parse( "summary:lucene OR summary:action" );
hibQuery = s.createFullTextQuery( query, Book.class );
sort = new Sort( new SortField( "publicationDate", SortField.STRING, true ) ); //DESC
hibQuery.setSort( sort );
result = hibQuery.list();
assertNotNull( result );
assertEquals( "Wrong number of test results.", 4, result.size() );
for (Book book : result) {
System.out.println(book.getSummary() + " : " + book.getPublicationDate() );
}