I'm currently constructing an SQL query in a Java web service using a PreparedStatement. My service takes in multiple optional parameters to filter this query, including one of the filters being an array of ids. I've currently accounted for the optional parameters being null (unspecified) by checking the values with nvl(), but this is not working for an IN clause.
My query currently looks like this:
SELECT
a.item_type
a.item_flag
a.item_id
FROM tableA a
WHERE
a.item_type = nvl(?, a.item_type)
AND a.item_flag = nvl(?, a.item_flag)
AND a.item_id IN nvl(?, a.item_id)
And I'm setting my prepared statement values with:
private void assignStatementValues(final PreparedStatement statement,
final String itemType, final int itemFlag,
final List<Long> itemIds) throws SQLException {
Integer itemFlag;
if (Strings.isNullOrEmpty(itemType)) {
statement.setNull(1, java.sql.Types.VARCHAR);
} else {
statement.setString(1, itemType);
}
if (itemFlag == null) {
statement.setNull(2, java.sql.Types.INTEGER);
} else {
statement.setInt(2, itemFlag);
}
if (itemIds == null) {
statement.setNull(3, java.sql.Types.ARRAY);
} else {
statement.setArray(3, statement.getConnection().createArrayOf("bigint", itemIds.toArray()));
}
statement.executeQuery();
}
Currently my query works with the optional parameters when the "AND...IN" clause is removed, but I receive a 500 response when the "AND...IN" clause is present. Is there a better way to structure my query for the optional list/array parameter?