【问题标题】:Can I ask JDBCTemplate to expand a list parameter for use in an in() clause? [duplicate]我可以要求 JDBCTemplate 扩展一个列表参数以在 in() 子句中使用吗? [复制]
【发布时间】:2011-04-06 13:06:41
【问题描述】:

我可以这样做吗:

select * from mytable m where m.group_id in (?)

...并传入要扩展的参数列表或数组到我的参数中,即:

select * from mytable m where m.group_id in (1,2,3,4)

具体来说,我使用的是 Spring 和 JdbcTemplate/SimpleJdbcTemplate 类。

【问题讨论】:

  • 我的记忆是否定的——? 占位符在 SQL 中表示单个值,因此它不能包含逗号分隔的列表。

标签: java spring jdbc spring-jdbc


【解决方案1】:

请找到下面的代码

public Collection<Employee> findByIds(List<String> ids) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("ids", ids);

        List<Employee> employees = namedParameterJdbcTemplate.query(
                "SELECT * FROM trn_employee where employee_id IN (:ids)",
                params,
                ParameterizedBeanPropertyRowMapper.newInstance(Employee.class));

        return employees;

    }

【讨论】:

    【解决方案2】:

    是的,您可以在 Spring 3 中使用命名参数。

    http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html#jdbc-in-clause

    它应该采用任何原语列表并扩展列表。请注意,您的列表不会超过数据库支持的最大大小。 (Oracle 限制为 1000)。像这样的东西应该可以工作:

        List<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
    
        Map<String,Object>  params = new HashMap<String, Object>();
    
        String sql = "SELECT PERSON.ID, PERSON.USERNAME, PERSON.EMAIL_ADDRESS, PERSON.FIRST_NAME, PERSON.LAST_NAME, PERSON.ACCOUNT_STATUS FROM PERSON WHERE ID IN (:ids)";
        params.put("ids",ids);
    
        return getSimpleJdbcTemplate().query(sql, rowMapper, params);
    

    【讨论】:

      【解决方案3】:

      您可以使用 NamedParameterJdbcTemplate 来做到这一点。

      你的样本会是这样的:

      NamedParameterJdbcTemplate db = ...;
      List paramList = ...;
      
      Map idsMap = Collections.singletonMap("ids", paramList);
      db.query("select * from mytable m where m.group_id in (:ids)", idsMap);
      

      【讨论】:

      • 谢谢!值得一提的是,可以从标准 JdbcTemplate 创建 NamedParameterJdbcTemplate: NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
      【解决方案4】:

      抱歉,不能这样做。您可以为自己编写一个方便的方法来做到这一点,但据我所知,没有像 Hibernate 这样的setParameterList()

      【讨论】:

      • 最简单的便捷方法,对于数字类型的列表可能是 list.toString().replace("[","(").replace("]",")")跨度>
      猜你喜欢
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      • 2012-04-28
      • 2023-02-18
      • 2019-10-22
      相关资源
      最近更新 更多