javacassandradatastax-java-driver

Does the Cassandra Java driver @Select annotation use Prepared Statements?


Does Cassandra DataStax's @Select annotation use PreparedStatements in the generated queries? Is it effective like if I use a PreparedStatement and execute it manually?


Solution

  • Yes, mappers also prepare the statements. If you observe the logs generated out of the mappers, you could see it prepare the statements for us. For e.g. when you configure logging you'll notice things like below when the mapper code is constructed,

    DEBUG ProductDaoImpl__MapperGenerated - [s0] Initializing new instance for keyspace = ks_0 and table = null
    DEBUG ProductHelper__MapperGenerated - [s0] Entity Product will be mapped to ks_0.product
    DEBUG ProductDaoImpl__MapperGenerated - [s0] Preparing query
          `SELECT id,description,dimensions FROM ks_0.product WHERE id=:id`
          for method findById(java.util.UUID)
    

    Optional / Bonus: As recommended in the DataStax Java Driver documentation here, you could & should definitely leverage PreparedStatements while working with QueryBuilder favoring bound statements for queries that are used often. You can still use the query builder and prepare the result:

      // During application initialization:
      Select selectUser = selectFrom("user").all().whereColumn("id").isEqualTo(bindMarker());
      // SELECT * FROM user WHERE id=?
      PreparedStatement preparedSelectUser = session.prepare(selectUser.build());
    
      // At runtime:
      session.execute(preparedSelectUser.bind(userId));