spring 如何通过Spring JdbcTemplate生成动态的“in(...)”sql列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1981683/
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-09-08 03:57:46  来源:igfitidea点击:

How to generate a dynamic "in (...)" sql list through Spring JdbcTemplate?

spring

提问by wsb3383

Is it possible to generate arbitrary "in ()" lists in a SQL query through Jdbc template:

是否可以通过 Jdbc 模板在 SQL 查询中生成任意“in()”列表:

example:

例子:

"select * from t where c in (#)" , However '#' could be an arbitrary list of values only known at runtime.

"select * from t where c in (#)" ,但是 '#' 可以是仅在运行时已知的任意值列表。

回答by axtavt

Yes, it's possible in Spring if you use NamedParameterJdbcTemplateor SimpleJdbcTemplatewith named parameters. List parameter can be set as a java.util.List:

是的,如果您使用NamedParameterJdbcTemplateSimpleJdbcTemplate命名参数,则在 Spring 中是可能的。列表参数可以设置为java.util.List

List<String> list = new ArrayList<String>();

list.add("A");
list.add("B");
list.add("C");

List<SomeObject> result = simpleJdbcTemplate.query("SELECT * FROM t WHERE c in (:list)",
    new RowMapper<SomeObject>() { ... },
    Collections.singletonMap("list", list));

In this case Spring internally creates the SQL query with the required number of placeholders based on the size of the actual list when replacing named parameters with ?s.

在这种情况下,当用?s替换命名参数时,Spring 在内部根据实际列表的大小创建具有所需数量占位符的 SQL 查询。

回答by James Zhou

In Hibernate , you can use following sample:

在 Hibernate 中,您可以使用以下示例:

if(tenors != null && tenors.length >0)
            sql.append(" and ip.tenor_id in (:tenors)");

.....


if(tenors != null && tenors.length >0){
    query.setParameterList("tenors", tenors);                                 
}
.....
SQLQuery query = (SQLQuery) getSession().createSQLQuery(sql.toString())

回答by Vins

SimpleJDBCTemplate is depricated now. You can use NamedParameterJdbcTemplate instead. Sample code is below. If you have multiple parameters of different kind you can use Objectas key, otherwise use your List<T>

SimpleJDBCTemplate 现在已弃用。您可以改用 NamedParameterJdbcTemplate。示例代码如下。如果您有多个不同类型的参数,您可以将其Object用作键,否则使用您的List<T>

String sqlAllEmpl = queryLoader.getProperty("allEmployeesByLevelAndPeriod");
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("level", levelStr);
        paramMap.put("periodList", periodList);

        gridList = namedParameterJdbcTemplate.query(sqlAllEmpl, paramMap, new YourRowMapper());

your sqlAllEmpl will have two place holders, level- string and periodList- which is a list used in the IN statement of sql.

您的 sqlAllEmpl 将有两个占位符,level- 字符串和periodList- 这是在 sql 的 IN 语句中使用的列表。