Home > Software engineering >  Convert from a list to an array of `SqlParameterSource`. A.K.A. convert a list to an array of maps
Convert from a list to an array of `SqlParameterSource`. A.K.A. convert a list to an array of maps

Time:01-06

I have a list of entities which I want to relate to another entity using JDBC named template. For that, I am inserting the ID pairs on the join table using a batch update operation, but the problem is that the way I have found to generate an array of SqlParameterSource is a little bit clunky. Is there any way of doing this with an stream instead?

// Create an array of the size of the fruit list.
final SqlParameterSource[] fruitParameters = new SqlParameterSource[tree.getFruits().size()];

// Get all the fruits to iterate through.
final List<Fruit> fruits = tree.getFruits();

// Fill the array with the parameter sources.
for (int i = 0; i < fruitIds.length; i  ) {
    final var fruit = fruits.get(i);

    final var parameters = new MapSqlParameterSource();
    parameters.addValue("fruit_id", fruit.getId());
    parameters.addValue("tree_id", tree.getId());

    fruitParameters[i] = parameters;
}

I think the problem boils down to converting a list to an array of maps.

Thank you very much in advance!

CodePudding user response:

 fruits.stream().map(fruit-> {
        var parameters = new MapSqlParameterSource();
        parameters.addValue("fruit_id", fruit.getId());
        parameters.addValue("tree_id", tree.getId());
        return parameters;
    }).toArray(SqlParameterSource[]::new);

if you can create method that take Fruit object and return MapSqlParameterSource would be better from readability point of view and you just call that method inside the map method

  • Related