微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java Spring不支持的StringMatcher REGEX

如何解决Java Spring不支持的StringMatcher REGEX

尝试将StringMatcher.REGEX与java spring一起使用时出现问题。没有编译器错误或任何错误,但是当您尝试使用上述字符串匹配器调用该项目时,会收到以下错误

2020-10-09 15:07:30.543 ERROR 29584 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing Failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Unsupported StringMatcher REGEX; nested exception is java.lang.IllegalArgumentException: Unsupported StringMatcher REGEX] with root cause

java.lang.IllegalArgumentException: Unsupported StringMatcher REGEX
    at org.springframework.data.jpa.convert.QueryByExamplePredicateBuilder.getPredicates(QueryByExamplePredicateBuilder.java:210) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
    at org.springframework.data.jpa.convert.QueryByExamplePredicateBuilder.getPredicate(QueryByExamplePredicateBuilder.java:102) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository$ExampleSpecification.toPredicate(SimpleJpaRepository.java:886) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.applySpecificationToCriteria(SimpleJpaRepository.java:762) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]

执行以下操作时会看到错误

ExampleMatcher matcher = ExampleMatcher
                                .matchingall()
                                .withStringMatcher(
                                        ExampleMatcher.StringMatcher.REGEX
                                 );

请注意,上面的代码可以很好地编译,执行时会发生错误

解决方法

首先,StringMatcher.REGEX是一个完全有效的值。正如您在ExampleMatcher.class文件中看到的那样,您有6个有效的StringMatcher选项:

    public static enum StringMatcher {
        DEFAULT,EXACT,STARTING,ENDING,CONTAINING,REGEX;

        private StringMatcher() {
        }
    }

因为它是一个有效的条目,所以代码可以正常编译并且没有问题。 问题在于regex选项仅适用于Java,不适用于Java Spring。春季文档示例查询指出:

Only supports starts/contains/ends/regex matching for strings and exact matching for other property types.

但是,事实并非如此。根据Spring的jira ticket的说法,不支持StringMatcher.REGEX,并且永远不会支持,因为并非所有数据库系统都支持它。基本上,您只能访问DEFAULT,EXACT,STARTING,ENDING和CONTAINING字符串匹配项,而REGEX将永远无法使用。我希望这个答案可以节省很多时间。我浪费太多时间试图弄清楚。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。