Chapter 4. Hibernate Lucene Integration

Lucene is a high-performance Java search engine library available from the Apache Software Foundation. Hibernate Annotations includes a package of annotations that allows you to mark any domain model object as indexable and have Hibernate maintain a Lucene index of any instances persisted via Hibernate.

4.1. Using Lucene to index your entities

4.1.1. Annotating your domain model

First, we must declare a persistent class as @Indexed:

@Entity
@Indexed(index="indexes/essays")
public class Essay {
    ...
}

The index attribute tells Hibernate where the Lucene index is located (a directory on your file system). If you wish to define a base directory for all lucene indexes, you can use the hibernate.lucene.index_dir property in your configuration file.

Lucene indexes contain four kinds of fields: keyword fields, text fields, unstored fields and unindexed fields. Hibernate Annotations provides annotations to mark a property of an entity as one of the first three kinds of indexed fields.

@Entity
@Indexed(index="indexes/essays")
public class Essay {
    ...

    @Id
    @Keyword(id=true)
    public Long getId() { return id; }
    
    @Text(name="Abstract")
    public String getSummary() { return summary; }
    
    @Lob
    @Unstored
    public String getText() { return text; }
    
}

These annotations define an index with three fields: Id, Abstract and Text.

Note: you must specify @Keyword(id=true) on the identifier property of your entity class.

The analyzer class used to index the elements is configurable through the hibernate.lucene.analyzer property. If none defined, org.apache.lucene.analysis.standard.StandardAnalyzer is used as the default.

4.1.2. Enabling automatic indexing

Finally, we enable the LuceneEventListener for the three Hibernate events that occur after changes are committed to the database.

<hibernate-configuration>
    ...
    <event type="post-commit-update" 
        <listener  
            class="org.hibernate.lucene.event.LuceneEventListener"/>
    </event>
    <event type="post-commit-insert" 
        <listener 
            class="org.hibernate.lucene.event.LuceneEventListener"/>
    </event>
    <event type="post-commit-delete" 
        <listener 
            class="org.hibernate.lucene.event.LuceneEventListener"/>
    </event>
</hibernate-configuration>