In integration tests, I often need to setup the database to a determined state before every test case. In order to do that, we need to create database schema which reflect your current models and then populate with proper data. In today post, I will show you how to generate the database schema from your Hibernate models by using the Hibernate Maven Plugin (3.0). In my shop, we are still using the "old-school" Hibernate mapping: XML!. The reason is we want to keep our models pristine (no annotations or whatever). We use Maven as our build tool, so here is the plugin configuration that works:


    org.codehaus.mojo
    hibernate3-maven-plugin
    3.0
    
        
            create-schema
            process-test-resources
            
                run
            
            
                
                    
                    
                
            
        
    

We use Spring to configure Hibernate directly, the hibernate.cfg.xml used here is just for this purpose only (ie. generating the database schema). Here is it just for the sake of completeness:



    
        org.hibernate.dialect.HSQLDialect
        org.hsqldb.jdbcDriver
        jdbc:hsqldb:mem:sample_db
        sa
        
    

There are other operations that you can utilize with Hibernate Tools. For more information, please refer to Hibernate Tools documentation and the hibernate3-maven-plugin site

.

I have a chance to use Lucene (3.6.0) to implement a full-text search in one of my recent projects. One of the requirements is to highlight the matched text in the result. The highlighted text should be displayed in the whole paragraph (not just a small text fragment). Here is my snippet to achieve this:

private String getHighlightedField(Query query, Analyzer analyzer, String fieldName, String fieldValue) throws IOException, InvalidTokenOffsetsException {
    Formatter formatter = new SimpleHTMLFormatter("", "");
    QueryScorer queryScorer = new QueryScorer(query);
    Highlighter highlighter = new Highlighter(formatter, queryScorer);
    highlighter.setTextFragmenter(new SimpleSpanFragmenter(queryScorer, Integer.MAX_VALUE));
    highlighter.setMaxDocCharsToAnalyze(Integer.MAX_VALUE);
    return highlighter.getBestFragment(this.analyzer, fieldName, fieldValue);
}
  • By creating a SimpleSpanFragmenter with a very big fragment size, we can display the highlighted text in the whole paragraph or document. Lucene also does a nice thing here for free, by merging all the highlighted text fragments into one big chunk (or our original paragraph/document)
  • query: is the Lucene query you constructed to do the search
  • analyzer: is the Lucene analyzer are used to analyzed the field when you create the index for that field

Happy highlighting!