Preparing the entity for Hibernate Search

Now that Hibernate knows about our domain object, we need to tell the Hibernate Search add-on how to manage it with Lucene.

We can use some advanced options to leverage the full power of Lucene, and as this application develops we will do just that. However, using Hibernate Search in a basic scenario is as simple as adding two annotations.

First, we'll add the @Indexed annotation to the class itself:

...
import org.hibernate.search.annotations.Indexed;
...
@Entity
@Indexed
public class App implements Serializable {
...

This simply declares that Lucene should build and use an index for this entity class. This annotation is optional. When you write a large-scale application, many of its entity classes may not be relevant to searching. Hibernate Search only needs to tell Lucene about those types that will be searchable.

Secondly, we will declare searchable data points with the @Field annotation:

...
import org.hibernate.search.annotations.Field;
...
@Id
@GeneratedValue
private Long id;
@Column
@Field
private String name;

@Column(length=1000)
@Field
private String description;

@Column
private String image;
...

Notice that we're only applying this annotation to the name and description member variables. We did not annotate image, because we don't care about searching for apps by their image filenames. We likewise did not annotate id, because you don't exactly need a powerful search engine to find a database table row by its primary key!

Note

Deciding what to annotate is a judgment call. The more entities you annotate for indexing, and the more member variables you annotate as fields, the more rich and powerful your Lucene indexes will be. However, if we annotate superfluous stuff just because we can, then we make Lucene do unnecessary work that can hurt performance.

In Chapter 7, Advanced Performance Strategies, we will explore such performance considerations in greater depth. Right now, we're all set to search for apps by name or description.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset