Use Regular Expressions in JPA CriteriaBuilder

后端 未结 3 458
南笙
南笙 2021-01-13 06:48

I\'m using the JPA CriteriaBuilder to select entities of type MyEntity from a MySQL db as follows:

String regExp = \"(abc|def)\"
CriteriaBuilder         


        
3条回答
  •  心在旅途
    2021-01-13 06:48

    I came across this recently and used the first post to implement the hibernate mysql function option.

    To help save some time for others this is what I did:

    set up the function in your custom dialect file in hibernate:

    public class MySQLDialect extends Dialect {
    
       public MySQLDialect() {
          super();
          ...
          registerFunction("regexp", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "?1 REGEXP ?2"));
          ...
       }
       ...
    }
    

    then within the criteria builder section:

    CriteriaBuilder builder = ...;    
    
    Pattern regexPattern = Pattern.compile("^[0-9]\\|[0-9]+");
    
    Expression patternExpression = builder.literal(regexPattern.pattern());
    
    Path path = ... ;// regex comparison column
    
    // regexp comes from the name of the regex function 
    // defined in the Mysql Dialect file above
    Predicate theRegexPredicate = builder.equal(builder.function("regexp", Integer.class, path, patternExpression), 1);
    

    Then use theRegexPredicate to construct the where clause in your CriteriaBuilder query.

提交回复
热议问题