0

I want to query the DB based on user input. For instance, if this input is "long red wire", the query must be:

SELECT * FROM foo WHERE tag ILIKE 'long' OR tag ILIKE 'red' OR tag ILIKE 'wire';
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

As you can see, the structure of the query changes with the input, it is not just the data.

Does Spring offer any functionality to cope with queries with variable structures? Or should I construct the string by myself?


This is somewhat what I have in mind.

SELECT * FROM foo WHERE {{tag = '?'} OR};

2 Answers 2

2

seems to me that you are interested in select statement "in", with spring you can do like this ...

   NamedParameterJdbcTemplate namedJdbcTemplate = new NamedParameterJdbcTemplate( jdbcTemplate.getDataSource() );

    Set<String> maps = new HashSet<String>();
    maps.add("long")
    maps.add("red")
    maps.add("wire")
    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("tags", maps  );                
    namedJdbcTemplate.query( "SELECT ... tags  in (:tags)" , params , new RowMapper() {

        @Override
        public Object mapRow(ResultSet rs, int arg1) throws SQLException {
             ....
        }
    });
Sign up to request clarification or add additional context in comments.

1 Comment

I had omitted it since I though it was not relevant for the question. Comparsion is made by "ILIKE" instead of "=" (I have already edited it). However, I could make a workaround that will let me use "=", therefore allowing me to use your answear (+1). I will wait a couple of days to see if someone knows a method to achieve exactly what I want, if not, I will mark your answear as valid.
1

First answer is correct one for this particular case where it can be represented as in expression.

If you want to build your query string in runtime - spring-jdbc doesn't support this out of the box. There are a lot of third-party libraries to do it, I also wrote one - query-string-builder, you may find links to others in the project readme.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.