简体   繁体   English

JPA 中谓词的表达式解析器

[英]Expression parser for Predicates in JPA

In a command line based application I want to offer basic support for filtering database results.在基于命令行的应用程序中,我想为过滤数据库结果提供基本支持。 For this, I need to parse user input.为此,我需要解析用户输入。 I want to support these tokens:我想支持这些令牌:

  • boolean (logical) operators including and , or , not and parentheses布尔(逻辑)运算符,包括andornot和括号
  • variables, strings, dates and numbers变量、字符串、日期和数字
  • comparison Operators: = , != , < , > , >= , <=比较运算符: = , != , < , > , >= , <=

So an input string could look like this:因此,输入字符串可能如下所示:

(age > 3 or name != 'tom') and city='london' and ((birthday=01.01.2010 or birthday >= 01.01.2013)) (age > 3 or name != 'tom') and city='london' and ((birthday=01.01.2010 orbirthday >= 01.01.2013))

Basic stuff.基本的东西。

Question : Where do I get a (tokenizer and) parser for that?问题:我在哪里可以获得(标记器和)解析器?

  • Are there libraries supporting these basics already?是否已经有支持这些基础知识的库?
  • If not, I know that there are tools to generate Java classes for Tokenizers and Parsers.如果没有,我知道有一些工具可以为 Tokenizers 和 Parsers 生成 Java 类。 Do you have any recommendations?你有什么建议?

I would then convert the results to JPA's Predicate s for the CriteriaQuery .然后我会将结果转换为CriteriaQuery JPA 的Predicate s。 First I thought, I could just offer JPQL in command line and let the user specify SQL based restrictions.首先我想,我可以在命令行中提供 JPQL 并让用户指定基于 SQL 的限制。 But I don't want to let the user write conditions that might stop working eg when the database schema changes.但我不想让用户编写可能停止工作的条件,例如当数据库模式更改时。

You are searching for some tokenizer and parser.您正在搜索一些标记器和解析器。

ANTLR is a lexer/parser generator, and the huge grammar repository that also, among others, contains SQL - even with dialects for some common databases at https://github.com/antlr/grammars-v4/tree/master/sql . ANTLR 是一个词法分析器/解析器生成器,以及巨大的语法存储库,其中还包含 SQL - 即使在https://github.com/antlr/grammars-v4/tree/master/sql上还包含一些常见数据库的方言。

So if you still have that problem, you can generate the parser for free and just care about translating the abstract syntax tree into JPA criteria calls.所以如果你仍然有这个问题,你可以免费生成解析器,只关心将抽象语法树转换成 JPA 标准调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM