Spring Data Cassandra and PreparedStatementCache

Nikem :

I don't understand how to achieve very simple goal with Spring Data Cassandra.

I want to execute an "INSERT" statement multiple times with different parameter values. I don't have mapped domain class at the moment, so I use CqlOperations interface provided by Spring Data.

When I just use execute(String cql, Object... args), Cassandra driver complains about "Re-preparing already prepared query is generally an anti-pattern and will likely affect performance. Consider preparing the statement only once". Because Spring Data uses SimplePreparedStatementCreator. But I don't see any way to tell Spring Data to use CachedPreparedStatementCreator instead. All I see is execute(PreparedStatementCreator psc) method which does not allow me to provide parameters values.

So, is there any way to either tell Spring Data to use proper statement cache or to achieve something similar to execute(PreparedStatementCreator, Object...)?

mp911de :

CqlTemplate exposes callback and customization hooks that allow for tailoring some of its functionality to the needs of your application.

CqlTemplate does intentionally come without caching as caching leads to time vs. space considerations. Spring Data Cassandra cannot make decisions as we cannot assume what applications typically require.

Spring Data Cassandra's package core.cql.support ships with support for CachedPreparedStatementCreator and a PreparedStatementCache that you can use for that purpose.

Subclass CqlTemplate and override its newPreparedStatementCreator(…) method to specify which PreparedStatementCreator to use. The following example shows an example for a cache with infinite retention:

public class MyCachedCqlTemplate extends CqlTemplate {

    PreparedStatementCache cache = MapPreparedStatementCache.create();

    @Override
    protected PreparedStatementCreator newPreparedStatementCreator(String cql) {
        return CachedPreparedStatementCreator.of(cache, cql);
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164165&siteId=1