简体   繁体   中英

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
  • 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))

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. Do you have any recommendations?

I would then convert the results to JPA's Predicate s for the CriteriaQuery . First I thought, I could just offer JPQL in command line and let the user specify SQL based restrictions. 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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