title: How to initialize Cassandra keyspace and tables with Spring boot
body: <p>I am using Cassandra as a datasource in my Spring boot application and would like to initialize the database before the application starts.</p>
  
  <p>Up to now what I have done is, I have defined a class "CassandraConfiguration" extending "AbstractCassandraConfiguration" class as in the examples which you can see below and I have a repository extending "CassandraRepository". When I create the keyspace and the table myself, the application works fine. </p>
  
  <p>However, I want to create the keyspace and tables automatically while application is starting. In order to do that, I supplied a schema.cql file under resources folder but I could not make that script work.</p>
  
  <p>Does anyone have any idea what can I do to create the keyspace(s) and tables automatically?</p>
  
  <p>Thanks.</p>
  
  <p>Edit: I am using Cassandra 2.0.9, spring-boot 1.3.2.RELEASE and datastax cassandra driver 2.1.6 versions.</p>
  
  <p>CassandraConfiguration.java</p>
  
  <pre><code>@Configuration
  @PropertySource(value = { "classpath:cassandra.properties" })
  @EnableCassandraRepositories(basePackages = { "bla.bla.bla.repository" })
  public class CassandraConfiguration extends AbstractCassandraConfiguration {
  
      @Autowired
      private Environment environment;
  
  
      @Bean
      public CassandraClusterFactoryBean cluster() {
          CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
          cluster.setContactPoints( environment.getProperty( "cassandra.contactpoints" ) );
          cluster.setPort( Integer.parseInt( environment.getProperty( "cassandra.port" ) ) );
          return cluster;
      }
  
  
      @Bean
      public CassandraMappingContext cassandraMapping() throws ClassNotFoundException {
          return new BasicCassandraMappingContext();
      }
  
  
      @Bean
      public CassandraConverter converter() throws ClassNotFoundException {
          return new MappingCassandraConverter(cassandraMapping());
      }
  
  
      @Override
      protected String getKeyspaceName() {
          return environment.getProperty( "cassandra.keyspace" );
      }
  
  
      @Bean
      public CassandraSessionFactoryBean session() throws Exception {
  
          CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
          session.setCluster(cluster().getObject());
          session.setKeyspaceName(environment.getProperty("cassandra.keyspace"));
          session.setConverter(converter());
          session.setSchemaAction(SchemaAction.NONE);
  
          return session;
      }
  
  
      @Override
      public SchemaAction getSchemaAction() {
          return SchemaAction.RECREATE_DROP_UNUSED;
      }
  }
  </code></pre>