java JDBCTemplate 查询多次使用参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25235466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 07:39:10  来源:igfitidea点击:

JDBCTemplate query use arguments many times

javamysqlsqljdbctemplate

提问by renz

In JDBCTemplate, I'm calling

在 JDBCTemplate 中,我正在调用

public <T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper) throws DataAccessException {
            return query(sql, args, new RowMapperResultSetExtractor<T>(rowMapper));
        }

with

getJdbcTemplate().query(usersByUsernameQuery, new String[] {username}, new RowMapper<UserDetails>()

My problem is I only have access to the usersByUsernameQueryargument, and I want to use the 'username' variable twice in it. For example:

我的问题是我只能访问usersByUsernameQuery参数,并且我想在其中两次使用 'username' 变量。例如:

usersByUsernameQuery = "Select * from ... ... where someColumn=? or anotherColumn=?" 

Since I'm only passing a string array with one element (username), how should I build my query?

由于我只传递一个包含一个元素(用户名)的字符串数组,我应该如何构建我的查询?

回答by Manish Kr. Shukla

You can pass the same argument twice in the jdbcTemplate..

您可以在 jdbcTemplate 中两次传递相同的参数。

getJdbcTemplate().query(usersByUsernameQuery, new String[] {username, username}, new RowMapper<UserDetails>()

This is completely valid and working.

这是完全有效且有效的。

Alternatively, you can go through the following thread if you can use a different variation of jdbcTemplate.query

或者,如果您可以使用 jdbcTemplate.query 的不同变体,您可以通过以下线程

How to execute IN() SQL queries with Spring's JDBCTemplate effectivly?

如何使用 Spring 的 JDBCTemplate 有效地执行 IN() SQL 查询?