user3486059 user3486059 - 1 year ago 194
MySQL Question

spring mvc Hibernate Search query

I am working with spring, using hibernate, maven and mysql, i'm trying to make a simple site for movies and actors. What i'd like is a search method, where you type a word, or part of a word/name and you will get some results, this is my query:

public List<Movie> searchForMovie(String searchText) {
FullTextSession fullTextSession = Search.getFullTextSession(getSession());

QueryBuilder qb = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Movie.class).get(); query = qb.keyword().onFields("year", "title").matching(searchText)

org.hibernate.Query hibQuery = fullTextSession.createFullTextQuery(query, Movie.class);

List<Movie> results = hibQuery.list();
return results;

As you can see, I am using 'keyword', this means you would have to search for the whole word/name, not only part of it. For example, if I want to find the movie 'hunger games' I would have to type 'hunger' or 'games', what I want is it to be possible to only write 'hunge' and still get results. I cant seem to find a query that will do this, thoughts?

Answer Source

You can use hibernate wildcard queries for this.

? - represents a single character
* - represents any character sequence.

Please also note that for performance purposes, it is recommended that query do not start with ? or either *.

   QueryBuilder qb = fullTextSession.getSearchFactory()
                .buildQueryBuilder().forEntity(Movie.class).get(); query = qb
                .keyword().wildcard().onFields("year", "title")
                .matching(searchText + "*")

See hibernate docs for complete reference. Wildcard Queries.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download