Use Regular Expressions in JPA CriteriaBuilder

后端 未结 3 489
南笙
南笙 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 07:08

    Maybe this snippet will help. We had to exclude characters in a search, and we using Oracle. CriteriaBuilder (at least as of 2.1) will let you call a function.

    private static final Pattern UNDESIRABLES = Pattern.compile("[(){},.;!?<>%_-]");
    private static final String UNDESIRABLE_REPLACEMENT = "";
    ...
    

    In the search method, create a Predicate to use in your where clause:

    Expression undesirables = cb.literal(UNDESIRABLES.toString());
    Expression replaceWith = cb.literal(UNDESIRABLE_REPLACEMENT);
    Expression regExp = cb.function("REGEXP_REPLACE", String.class, client.get(Client_.companyName),
        undesirables, replaceWith);
    Predicate companyNameMatch = cb.equal(cb.trim(cb.lower(regExp)), removeUndesireables(name).trim());
    ...
    

    And create a method for the right hand comapare that uses the same values as the left:

    private String removeUndesireables(String name) {
        return UNDESIRABLES.matcher(name).replaceAll(UNDESIRABLE_REPLACEMENT).toLowerCase();
    }
    

提交回复
热议问题