问题
I would like to query a jsonb column in a PostgreSQL databse from a Java / Spring Boot application.
The structure of the jsonb documents is not known beforehand, although all the documents will have the same structure. The structure of the documents in the jsonb column is described in database tables.
The application obtains the jsonb document structure description from the database. The next step is running analytical queries on the jsonb data.
The analytical queries have to be assembled dynamically as the structure of the jsonb data is not known at the development time. How could the queries be created in the Java code without concatenating strings manually?
I am afraid that assembling the queries manually would be complex, unreadable and potentially create SQLi vulnerabilities.
回答1:
You can't. If you need to dynamically build a SQL query from meta-data stored in other tables, then you have to build the SQL using string concatenation.
I applaud you for being aware and concerned about SQL Injection vulnerabilities, however that is only a concern when using user-supplied values.
If the meta-data is guaranteed to be safe, then you can safely use that meta-data to dynamically build a SQL statement. If the meta-data is entered by a user, i.e. it is user-supplied, you have three choice:
Validate meta-data on entry, e.g. ensure that field names are valid names.
Encode meta-data when building SQL. This means quoting field names. If meta-data includes values (e.g. for filtering), values should be inserted into SQL as
?
parameter markers and the actual values given to thePreparedStatement
object.Both of the above. Double-guarding is a good thing.
来源:https://stackoverflow.com/questions/43713032/approaches-to-dynamically-assemble-postgresql-jsonb-queries-without-string-conca