I\'m using the JPA CriteriaBuilder to select entities of type MyEntity
from a MySQL db as follows:
String regExp = \"(abc|def)\"
CriteriaBuilder
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.