3
votes

I'm trying to persist an object to cassandra through BatchStatement

import com.datastax.driver.mapping.Mapper;

batch.add(mapper.saveQuery(itr.next()));

And i want to have IF NOT EXISTS clause like

INSERT INTO customer_account (customerID, customer_email) 
VALUES (‘LauraS’, ‘[email protected]’)
IF NOT EXISTS;

How should i implement IF NOT EXISTS through saveQuery?

1

1 Answers

5
votes

Unfortunately mapping API supports only simple CRUD operations, so light weight transaction is not possible in this context. You can use two ways to work around this:

  1. Use mapping Accessors, then your code would looks like accessor interface:

    @Accessor
    public interface UserAccessor {
        @Query("INSERT INTO sandbox.user (user_id, name) VALUES (:userId, :name) IF NOT EXISTS")
        Statement insertUser(@Param("userId") UUID userId, @Param("name") String name);
    }
    

    somewhere in the code:

    Statement statement = userAccessor.insertUser(user.getUserId(), user.getName());
    

    and then you could put statement in the BatchStatement

  2. Use query builder:

    Insert insert = new QueryBuilder(cluster).insertInto("sundbox", "user")
            .value("user_id", user.getUserId())
            .value("name", user.getName())
            .ifNotExists();
    

    Insert is a subtype of Statement, so you could put it in the BatchStatement as well. Take in to attention, I use Driver 2.2.0, so I use new QueryBuilder(cluster).insertInto(... In the case if you use lower driver version, you should use QueryBuilder.insertInto(...