Reputation: 326
I need Prepared Statement / instead of Query Builder using Cassandra Operations Interface and session Any Example or recent docs. for Cassandra using java
Upvotes: 0
Views: 7419
Reputation: 379
Use spring-data-cassandra and that will do all magic for you.
App sample https://github.com/valchkou-app/spring-boot-cassandra-simple
@Repository
interface ISensorMeasureRepository extends CassandraRepository<SensorMeasureEntity> {
@Query('select * from sensor_measures_simple where sensor_id=?0 and measure_time>=?1 and measure_time<=?2')
List<SensorMeasureEntity> getBySensorAndDateRange(int sensorId, Date start, Date end)
@Query('select * from sensor_measures_simple where sensor_id=?0 ALLOW FILTERING')
Stream<SensorMeasureEntity> getAllBySensor(int sensorId)
}
Upvotes: 1
Reputation: 1621
See this to check how to use prepared statment while using java datastax driver.
However i would recommend to store all preparedstatments in a cache (for example a map) while application initializes and reuse the same whenever requreid by creating boundstatment out of it. For example :
//Here Key is query string
private static final Map<String, PreparedStatement> psMap = new ConcurrentHashMap<String, PreparedStatement>();
//Will be invoked @ initialization
public void init(Session session) {
this.session = session;
for (QuerySetEnum cql : QuerySetEnum.values()) {
psMap.put(cql.getStatement(), session.prepare(cql.getStatement()));
}
//In Dao Impl class
//Get bounded statment + execute by passing the value
@Override
public void decreaseStats(long size, long count, String mapname,
int bucketId) {
BoundStatement boundStatement = getBoundStatement(QuerySetEnum.DECREASE_STATS);
metaTemplate.execute(boundStatement.bind(size, count, mapname,
bucketId));
}
//Below is the implementation how to get BoundStatement out to prepared statment cache
private BoundStatement getBoundStatement(QuerySetEnum query) {
PreparedStatement preparedStatement = queryPool
.getPreparedStatement(query);
BoundStatement boundStatement = new BoundStatement(preparedStatement);
return boundStatement;
}
Upvotes: 1
Reputation: 3024
For spring-data-cassandra v1.x, the getSession() method of org.springframework.cassandra.core.CqlOperations could let you access Session directly. However, similar APIs are deprecated since v2.0
Here is a example from https://github.com/opencredo/spring-data-cassandra-example/
@Autowired
private CqlOperations cqlTemplate;//or inherited interface, like CassandraOperations
private void insertEventUsingPreparedStatement() {
PreparedStatement preparedStatement = cqlTemplate.getSession().prepare("insert into event (id, type, bucket, tags) values (?, ?, ?, ?)");
Statement insertStatement = preparedStatement.bind(UUIDs.timeBased(), "type2", TIME_BUCKET, ImmutableSet.of("tag1", "tag2"));
cqlTemplate.execute(insertStatement);
}
Upvotes: 1