Spring批量动态IN查询

Spring batch dynamic IN Query

以下 ItemReader 获取需要从 MD 数据库中检索的数千个帐户的列表。

在这种方法中,我可以使用的帐户数量有限:

@StepScope
@Bean
public ItemReader<OmsDto> itemReader(@Value("#{stepExecutionContext[accOms]}") List<String> notLoadedFiles) {

    StringBuffer buffer = new StringBuffer();
    notLoadedFiles.forEach(accountNumber -> buffer.append("'"+accountNumber+"',"));
    buffer.replace(buffer.length()- 1, buffer.length(), "");
    
    DriverManagerDataSource mdDataSource = new DriverManagerDataSource();
    mdDataSource.setDriverClassName("prestosql");
    mdDataSource.setUrl("jdbc:presto:....");
    mdDataSource.setUsername(".....");
    mdDataSource.setPassword("....");

    String sql ="SELECT DISTINCT "
             .....
             .....
            + "FROM MD.ONLINE WHERE acct IN ";
    JdbcCursorItemReader<OmsDto> reader = new JdbcCursorItemReader<OmsDto>();
    
    reader.setVerifyCursorPosition(false);
    reader.setDataSource(mdDataSource);
    reader.setSql(sql);
    reader.open(new ExecutionContext());
    BeanPropertyRowMapper<OmsDto> rowMapper = new BeanPropertyRowMapper<>(OmsDto.class);
    rowMapper.setPrimitivesDefaultedForNullValue(true);
    reader.setRowMapper(rowMapper);
    return reader;
}

创建动态 IN 查询(​​WHERE A IN (…, .., …))的正确方法是什么?

谢谢

下面是一个动态生成 IN 查询的例子,

示例查询:SELECT * FROM USER WHERE ID IN (?,?,?,?,?)

 List ids = List.of(1,2,3,4,5);
    
 String inParams = String.join(",", ids.stream().map(id -> "?").collect(Collectors.toList()));


String query = String.format("SELECT * FROM USER WHERE ID IN (%s)", inParams); 

请注意,如果您的查询 IN 子句参数限制超过 1000 个,最好使用 TEMP 表。这里有一些关于 github

的例子