I’ve to write HQL based engine that patch HQL queries on the fly dynamically add joins and where parts (to prevent questions – I must use HQL, not criteria API).
E.g. inject to HQL from Object a something like from Object a JOIN a.path b WHERE b.id='XYZ'
I see a several options, but neither work for me:
-
Java
String.insert()approach. Find position of WHERE statement and add joins before and other part after the statement. It’s not a trivial task for HQL like thisSELECT a, (SELECT b FROM Object2 b WHERE b.path=a) FROM Object a WHERE EXISTS(SELECT 1 FROM … WHERE)
Pending algorithm: I could calculate number of brackets () before each WHERE and if it zero – I found correct WHERE position. Could anybody propose me a simpler algorithm or simple implementation on Java my one?
2.I suspect that my task could be solved via regular expressions, but can’t write correct regular expression for String.replace()
3.I saw AST/ANTLR based grammar and could parse my HQL, but don’t see a way how it could help me (i.e. I’ve got statement, but not position of correct statement WHERE).
4.Standalone libs exists for SQL parsing, but not for HQL.
Anyway, thanks for any thoughts 🙂
I followed path #1. It wasn’t as complex as I expected:
Code expectation
pFindPartmust be in format ” WHERE ” or ” FROM “.