Case-insensitive search using Hibernate

前端 未结 9 1175
长情又很酷
长情又很酷 2021-01-30 16:13

I\'m using Hibernate for ORM of my Java app to an Oracle database (not that the database vendor matters, we may switch to another database one day), and I want to retrieve objec

相关标签:
9条回答
  • 2021-01-30 16:43

    Since Hibernate 5.2 session.createCriteria is deprecated. Below is solution using JPA 2 CriteriaBuilder. It uses like and upper:

        CriteriaBuilder builder = session.getCriteriaBuilder();
        CriteriaQuery<Person> criteria = builder.createQuery(Person.class);
        Root<Person> root = criteria.from(Person.class);
    
        Expression<String> upper = builder.upper(root.get("town"));
        criteria.where(builder.like(upper, "%FRAN%"));
    
        session.createQuery(criteria.select(root)).getResultList();
    
    0 讨论(0)
  • 2021-01-30 16:49

    This can also be done using the criterion Example, in the org.hibernate.criterion package.

    public List findLike(Object entity, MatchMode matchMode) {
        Example example = Example.create(entity);
        example.enableLike(matchMode);
        example.ignoreCase();
        return getSession().createCriteria(entity.getClass()).add(
                example).list();
    }
    

    Just another way that I find useful to accomplish the above.

    0 讨论(0)
  • 2021-01-30 16:50

    You could look at using Compass a wrapper above lucene.

    http://www.compass-project.org/

    By adding a few annotations to your domain objects you get achieve this kind of thing.

    Compass provides a simple API for working with Lucene. If you know how to use an ORM, then you will feel right at home with Compass with simple operations for save, and delete & query.

    From the site itself. "Building on top of Lucene, Compass simplifies common usage patterns of Lucene such as google-style search, index updates as well as more advanced concepts such as caching and index sharding (sub indexes). Compass also uses built in optimizations for concurrent commits and merges."

    I have used this in the past and I find it great.

    0 讨论(0)
  • 2021-01-30 16:53

    For the simple case you describe, look at Restrictions.ilike(), which does a case-insensitive search.

    Criteria crit = session.createCriteria(Person.class);
    crit.add(Restrictions.ilike('town', '%fran%');
    List results = crit.list();
    
    0 讨论(0)
  • 2021-01-30 16:54

    You also do not have to put in the '%' wildcards. You can pass MatchMode (docs for previous releases here) in to tell the search how to behave. START, ANYWHERE, EXACT, and END matches are the options.

    0 讨论(0)
  • 2021-01-30 16:57
    Criteria crit = session.createCriteria(Person.class);
    crit.add(Restrictions.ilike('town', 'fran', MatchMode.ANYWHERE);
    List results = crit.list();
    
    0 讨论(0)
提交回复
热议问题