I'm in a situation where I have a parent class
class Parent<T extends Entity> {
...
public List<T> selectSomething() {
String sql = "SELECT " + getColumns() + " FROM " + getTable() + " WHERE ...";
TypedQuery<T> query = this.entityManager.createQuery(sql, T.class);
return query.getResultList();
}
}
(For sake of simplicity, there is only a method described but in practice there are more with the same format)
And many child classes :
class Child1 extends Parent<EntityChild1> { ... }
class Child2 extends Parent<EntityChild2> { ... }
...
class Child50 extends Parent<EntityChild50> { ... }
My issue is that this piece of code in the Parent
is detected as a security issue by tools like SonarQube for possible SQL injection, and this warning is a blocking point that I need to correct or bypass.
I precise the both method getColumns() and getTables() are 100% controlled by me and I do know for sure that there is no way for a user to interfere in any way with the returned values of those methods. So even if it's detected as SQL injection, I do know it's not one.
To fix this, I can't just use a prepared statement since the whole point of a prepared statement is to prevent to inject SQL code, so you can't use them for dynamic columns name or table name.
I'm considering two options :
Make the
selectSomething
method from theParent
abstract and reimplement it in each child with a fixed string for the request directly containing the table name and columns name.
This would work fine and fix the warning, but due to the high number ofChild
it makes the code much less maintainable and evolutive (especially considering that the number ofChild
class could increase over time).Simply let it as is and use a
@SupressWarning
annotation in theselectSomething
method from theParent
this make the tools like SonarQube ignore this.
Again, it's a solution that would work but which is not very clean and filling code with many@SupressWarning
is a bad practice.
Is there any good way to handle this situation ? If not, is there any reason I should stick with a solution above the other ?