Datastax cassandra object mapper setting consistency and if not exists

1.3k views Asked by At

I created entity which is annotated with @Table and it resembles my cassandra table. I can do save, get and everything without much problems.

My problem comes when I want to do something more exciting, like set consistency level or do if not exists insert or something like that. Basically there is annotation option for @Table where you can configure read and write consistency but what if you use Spring and set that through configuration file? I really like having external configuration for those things. Also how to do if not exists save?

I know that you can get saveQuery or getQuery as Statement and from it you can set consistency at least but it looks ugly, then you must take result set, do map and get your object.

Have two questions:

  • Is there a better way of dynamically setting consistency level for object mapper actions both with accessor and entity?
  • How to do if not exists save for mapped object?
2

There are 2 answers

0
GAK On

I understand this a very old question. but some of the answers here are outdated hence, I am adding my answer here.

With driver version 4.x you can use the @StatementAttributes annotation to set the consistency level and other statement attributes for each of the mapper dao methods.

@Dao 
 public interface ProductDao {   
    @Select  
    @StatementAttributes(consistencyLevel = "ONE", pageSize = 500)  
    Product findById(int productId); 
}
0
Den Roman On

How to do if not exists save for mapped object?

You will need to use accessor interface and specify your custom query there. If you need to udate only a small subset of fields that will work perfectly.

If you need to save the whole object with IF NOT EXISTS it could be done using two steps: first to update a specfic field with IF NOT EXISTS to logically say that row is being updating and second to save the object to that row using mapper.save operation. It all depends on whether it is sutable for your app logic.

docs from cassandra

It could be wrapped into yout Dao object that uses mapper.save/load for simple operations.