Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How create table with spring data cassandara?

I have created my own repository like that:

public interface MyRepository extends TypedIdCassandraRepository<MyEntity, String> {
}

So the question how automatically create cassandra table for that? Currently Spring injects MyRepository which tries to insert entity to non-existent table.

So is there a way to create cassandra tables (if they do not exist) during spring container start up?

P.S. It would be very nice if there is just config boolean property without adding lines of xml and creation something like BeanFactory and etc. :-)

like image 661
Cherry Avatar asked Aug 18 '14 06:08

Cherry


2 Answers

Actually, after digging into the source code located in spring-data-cassandra:3.1.9, you can check the implementation:

org.springframework.data.cassandra.config.SessionFactoryFactoryBean#performSchemaAction

with implementation as following:

protected void performSchemaAction() throws Exception {

    boolean create = false;
    boolean drop = DEFAULT_DROP_TABLES;
    boolean dropUnused = DEFAULT_DROP_UNUSED_TABLES;
    boolean ifNotExists = DEFAULT_CREATE_IF_NOT_EXISTS;

    switch (this.schemaAction) {
        case RECREATE_DROP_UNUSED:
            dropUnused = true;
        case RECREATE:
            drop = true;
        case CREATE_IF_NOT_EXISTS:
            ifNotExists = SchemaAction.CREATE_IF_NOT_EXISTS.equals(this.schemaAction);
        case CREATE:
            create = true;
        case NONE:
        default:
            // do nothing
    }

    if (create) {
        createTables(drop, dropUnused, ifNotExists);
    }
}

which means you have to assign CREATE to schemaAction if the table has never been created. And CREATE_IF_NOT_EXISTS dose not work.


More information please check here: Why `spring-data-jpa` with `spring-data-cassandra` won't create cassandra tables automatically?

like image 128
Gemini Keith Avatar answered Oct 31 '22 18:10

Gemini Keith


You can use this config in the application.properties

spring.data.cassandra.schema-action=CREATE_IF_NOT_EXISTS
like image 27
abbas Avatar answered Oct 31 '22 18:10

abbas