How to execute IN() SQL queries with Spring's JDBCTemplate effectively?
You want a parameter source:
Set<Integer> ids = ...;
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", ids);
List<Foo> foo = getJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",
parameters, getRowMapper());
This only works if getJdbcTemplate()
returns an instance of type NamedParameterJdbcTemplate
Can I execute a plain SQL statement with the Spring JDBC template?
From my point of view:
- a non-plain sql is a query in jql.
- Some stuff is quite complicate to achive with jql (ie. joins over a few tables) in an already existent data scheme.
- jpa requests primary keys in tables - which is not always the case in existent databases
- the question aims on 'i wanna have a fallback to traditional queries to do my everyday's life'
Is there a better way to execute this SQL statement in Spring using JdbcTemplate?
Yes.If you directly use the request param on your sql it can lead to SQL injection attacks. We can always go with the prepared statement by adding a placeholder to where the values must be added.
Use queryForList(String sql, Object... args)
or queryForList(String sql, Object[] args, Class<T> elementType)
Eg:-
String employeeId= "1";
String sql = "select id,name,address from employee where id = ?";
getJdbcTemplate(). queryForList(sql, new Object[]{employeeId}, Employee.class);
JdbcTemplate IN Clause for String elements
There a few other similar questions out there which might have helpful answers for you:
How to execute IN() SQL queries with Spring's JDBCTemplate effectivly?
To make this style of query work on my end, I have to switch from plain old JDBCTemplate to NamedParameterJdbcTemplate
.
Here is some example code:
String query = "select * from table where columnName in (:listOfValues)";
List<String> nameRecordIDs = new ArrayList<String>();
// ...
// add values to collection, then
// ...
Map namedParameters = Collections.singletonMap("listOfValues", nameRecordIDs);
namedparameterJdbcTemplate.query(query, namedParameters,new MyMapper());
Related Topics
How to Extract a Substring Using Regex
What Is the "Execute Around" Idiom
How to Fix an Unsatisfiedlinkerror (Can't Find Dependent Libraries) in a Jni Project
How to Kill a Thread? Without Using Stop();
Re-Paint on Translucent Frame/Panel/Component
Static Method in a Generic Class
Why Doesn't Java Send the Client Certificate During Ssl Handshake
Java Securityexception: Signer Information Does Not Match
What Does the Arrow Operator, '->', Do in Java
Replace Implicit Wait with Explicit Wait (Selenium Webdriver & Java)
How Does Cloneable Work in Java and How to Use It
How to Find the Duration of Difference Between Two Dates in Java
How to Count the Number of Occurrences of an Element in a List
How to Know If Other Threads Have Finished
How to Resolve the "Java.Net.Bindexception: Address Already in Use: Jvm_Bind" Error