brain storm
brain storm

Reputation: 31262

Prepared statements vs Bound statements in Cassandra?

I am wondering what is the advantage of using BoundStatement over PreparedStatement?

PreparedStatement statement = session.prepare(
                      "INSERT INTO simplex.songs " +
                      "(id, title, album, artist) " +
                      "VALUES (?, ?, ?, ?);");

BoundStatement boundStatement = new BoundStatement(statement);
            session.execute(boundStatement.bind(
                  UUID.fromString("756716f7-2e54-4715-9f00-91debea6cf50"),
                  "La Petite Tonkinoise",
                  "Bye Bye Blackbird",
                  "Joséphine Baker");

The simplest way would be:

PreparedStatement ps = session.prepare(
                      "INSERT INTO simplex.songs " +
                      "(id, title, album, artist, tags) " +
                      "VALUES (?, ?, ?, ?, ?);");
ps.bind(UUID.fromString("756716f7-2e54-4715-9f00-91debea6cf50"),
                      "La Petite Tonkinoise",
                      "Bye Bye Blackbird",
                      "Joséphine Baker");

As you can see, I can bind data to preparedStatement without boundStatements. Where are boundStatement useful?

Upvotes: 10

Views: 8515

Answers (2)

Krzysztof Czerw
Krzysztof Czerw

Reputation: 11

For me BoundStatement is created automatically when you invoke bind(...) on PreparedStatement. Also you can create instance BoundStatement directly.

PreparedStatement and BoundStatement has different behavior because PreparedStatement.bind() return new instance BoundStatement, while BoundStatement.bind() return himself.

It is important detail in multithreaded enviroment. Invoking method .bind() on shared BoundStatement result hazard

// shared instance BoundStatement on few threads 
BoundStatement bs1 = 
// bs2 is the same as bs1
// param1, param2, ... are different for every thread
BoundStatement bs2 = bs1.bind(param1, param2, ...);
// add some time to wait so other thread can modify your params
// Thread.sleep(RandomUtils.nextInt(100));        
// result2 sometimes may be with incorrect result 
results2 = session.execute(bs2); 

When you invoke bind on PreparedStatement you will get different instance of object and it is thread safe. (In the same scenario as above)

PreparedStatement ps1 = 
BoundStatement bs2 = ps1.bind(param1, param2, ...);
results2 = session.execute(bs2); 

Upvotes: 1

Carlo Bertuccini
Carlo Bertuccini

Reputation: 20051

No advantage: a BoundStatement is nothing more than a PreparedStatement with variables bounded. The bind() method of a PreparedStatements, in fact, returns a BoundStatement.

Upvotes: 10

Related Questions