deiga
deiga

Reputation: 1637

How to bind a collection of values to a jOOQ batch insert

I have a collection of objects, which I'd love to insert as a batch. First I thought "for-loops", but then it dawned on me that this should be doable with streams.

BatchBindStep userLoginBatch = create
    .batch(
            create.insertInto(USERLOGIN, USERLOGIN.USERNAME, USERLOGIN.IP, USERLOGIN.MAC, USERLOGIN.LOGIN, USERLOGIN.STATUS, USERLOGIN.APPLICATION, USERLOGIN.ENTERTAINMENT_CREDENTIALS_ID, USERLOGIN.VERSION)
                    .values(null, null, null, (Timestamp) null, null, null, (Integer) null, null)
    );

userLoginsToPersist
  .stream()
  .map(login ->
        Arrays.asList(login.getUsername(), login.getIp(), login.getMac(), login.getLogin(), login.getStatus(), login.getApplication(), login.getEntertainmentCredentialsId(), login.getVersion())
  ).reduce(userLoginBatch, (a, b) -> a.bind(b));
userLoginBatch.execute();

This is what I currently have and it's complaining that I can't reduce on that object...

Upvotes: 2

Views: 2505

Answers (3)

Marco
Marco

Reputation: 1575

The code will be much simpler if you use the forEach method:

userLoginsToPersist.forEach(login ->
    userLoginBatch.bind(login.getUsername(), login.getIp(), login.getMac(), login.getLogin(), login.getStatus(), login.getApplication(), login.getEntertainmentCredentialsId(), login.getVersion()));
userLoginBatch.execute();

Upvotes: 0

Tagir Valeev
Tagir Valeev

Reputation: 100269

Using reduce here abuses the API as your accumulator is not associative and your identity is not the actual identity. If you are already using jOOQ, it seems quite natural to use jOOL which foldLeft method is more suitable here:

Seq.seq(userLoginsToPersist)
   .map(login ->
     Arrays.asList(login.getUsername(), login.getIp(), login.getMac(),
                  login.getLogin(), login.getStatus(), login.getApplication(),
                  login.getEntertainmentCredentialsId(), login.getVersion()))
   .foldLeft(userLoginBatch, (a, b) -> a.bind(b))
   .execute();

Upvotes: 2

Jean Logeart
Jean Logeart

Reputation: 53839

You need to use reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner):

userLoginsToPersist
  .stream()
  .map(login ->
        Arrays.asList(login.getUsername(), login.getIp(), login.getMac(), login.getLogin(), login.getStatus(), login.getApplication(), login.getEntertainmentCredentialsId(), login.getVersion())
  ).reduce(userLoginBatch, (b, v) -> b.bind(v), (b1, b2) -> b1)
  .execute();

Upvotes: 3

Related Questions