Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-using PreparedStatement when using Datastax Cassandra Driver?

I'm currently using the Datastax Cassandra driver for Cassandra 2 to execute cql3. This works correctly. I started using PreparedStatement's:

Session session = sessionProvider.getSession();
try {
    PreparedStatement ps = session.prepare(cql);
    ResultSet rs = session.execute(ps.bind(objects));
    if (irsr != null) {
       irsr.read(rs);
    }
}

Sometimes I get a warning from the driver in my log:

Re-preparing already prepared query . Please note that preparing the same query more than once is generally an anti-pattern and will likely affect performance. Consider preparing the statement only once.

This warning makes sense, but i'm not sure how i should reuse the PreparedStatement?

Should I just create all my PreparedStatement in a constructor/init method and than simply use them?

But does this go well when multiple threads use the same PreparedStatement at the same time (especially calling PreparedStatement.bind() to bind objects)

like image 613
TinusSky Avatar asked Apr 07 '14 14:04

TinusSky


People also ask

How do I use a prepared statement in cassandra?

A prepared statement is a cassandra query that has been pre-parsed and validated by the cassandra database. Ideally you prepare a query once, and then use it many times by binding values to binding variables in the query.

What is PT2S cassandra?

PT2S is a duration of 2 seconds expressed in ISO 8601 format. The driver timeout exception is thrown when the driver-side basic. request. timeout is less than the server-side timeout. The default request timeouts in cassandra.

What is a bound statement?

A prepared statement with values bound to the bind variables. Once values has been provided for the variables of the PreparedStatement it has been created from, such BoundStatement can be executed (through Session. execute(Statement) ). The values of a BoundStatement can be set by either index or name.


1 Answers

You may just initialize the PreparedStatement once and cache it while the app is running. It should be available for use as long as the Cassandra cluster is up.

Using the statement from multiple threads is fine (as long as you don't modify it throught setXXX() methods). When you call bind(), the code underneath only reads the PreparedStatement and then creates a new instance of BoundStatement() which the caller thread is then free to mutate.

Here is the source code, if you're curious (search for bind()).

like image 190
Daniel S. Avatar answered Sep 28 '22 16:09

Daniel S.