Split and Join

Avagy funkcionális örömök java-ban.

Néha előfordul, hogy egy SQL IN close részébe eszeveszett méretű adatot akarok átadni. De azért mindig vannak technikai limitek. Ekkor jön jó az “oszd meg és uralkodj” megoldások.

 1public static <T> List<T> split_and_join (Collection<Long> ids, int max, Function<Collection<Long>, List<T>> op) {
 2    if (ids.size() > max) {
 3      Iterable<T> init = ImmutableList.of();
 4      for (List<Long> partIds : Iterables. partition(ids, max)) {
 5        init = Iterables.concat(init, op.apply(partIds));
 6      }
 7      return ImmutableList.copyOf(init);
 8    }
 9    return op.apply(ids);
10}

Example usage:

 1public List<BoothDto> getBooths(Collection<Long> sess_uids) {
 2    //@formatter:off
 3    final String sql =
 4      "        SELECT * "+
 5      "      FROM  "+
 6      "        SERVICE_ASSIGNMENTS sras "+
 7      "      WHERE sras.sess_sess_uid in (:sess_uids) ";
 8      //@formatter:on
 9    return SplitAndJoin. split_and_join(sess_uids, IN_CLOSE_MAX, new Function<Collection<Long>, List<BoothDto>>() {
10      public List<BoothDto> apply(Collection<Long> input) {
11        return namedTemplate .query(sql, ImmutableMap.of ("sess_uids" , input),
12            new BeanPropertyRowMapper<BoothDto>(BoothDto.class));
13      }
14    });
15}
Jul 29, 2013
comments powered by Disqus

Links

Cool

RSS