How to use MySQL's full text search from JPA

前端 未结 7 1905
谎友^
谎友^ 2020-12-15 13:55

I want to use MySQL\'s full text search features using JPA, without having to use a native query.

I am using EclipseLink, which has a function to support native SQL

7条回答
  •  难免孤独
    2020-12-15 14:38

    An improved answer of @Markus Barthlen which works for Hibernate.

    Create custom dialect

    public class MySQLDialectCustom extends MySQL5Dialect {
      public MySQLDialect() {
        super();
        registerFunction("match", new SQLFunctionTemplate(StandardBasicTypes.DOUBLE,
            "match(?1) against  (?2 in boolean mode)"));
      }
    }
    

    and register it by setting hibernate.dialect property.

    Use it

    in JPQL:

    Query query = entityManager
        .createQuery("select an from Animal an " +
                 "where an.type = :animalTypeNo " +
                 "and match(an.name, :animalName) > 0", Animal.class)
        .setParameter("animalType", "Mammal")
        .setParameter("animalName", "Tiger");
    List result = query.getResultList();
    return result;
    

    or with Criteria API:

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Animal.class);
    Root root = criteriaQuery.from(Animal.class);
    
    List predicates = new ArrayList<>();
    
    Expression match = criteriaBuilder.function("match", Double.class, root.get("name"),
    criteriaBuilder.parameter(String.class, "animalName"));
    
    predicates.add(criteriaBuilder.equal(root.get("animalType"), "Mammal"));
    predicates.add(criteriaBuilder.greaterThan(match, 0.));
    
    criteriaQuery.where(predicates.toArray(new Predicate[]{}));
    
    TypedQuery query = entityManager.createQuery(criteriaQuery);
    List result = query.setParameter("animalName", "Tiger").getResultList();
    
    return result;
    

    Some more details in this blog post: http://pavelmakhov.com/2016/09/jpa-custom-function

提交回复
热议问题