Spring : Can a class be both @Document and @Table

2019-07-22 16:15发布

问题:

I am using spring in MVC context. I am working with Cassandra and MonogDB. For the project, I have to make my models and dao classes compatible with both databases. Is it possible to have the same model class be @Document and also be @Table? Will spring be able to make the distinction at runtime?

For example, for mongo i will have

@Document
public class Book{

    @Id
    private String uniqueId;

    /*Other details*/
}

and for cassandra i will have

@Table
public class Book{

    @PrimaryKeyColumn(name = "uniqueId", ordinal = 0, type = PrimaryKeyType.PARTITIONED, ordering = Ordering.ASCENDING)
    private String uniqueId;

    /*Other details*/
}

can i have something like

@Table
@Document
public class Book{

    @PrimaryKeyColumn(name = "uniqueId", ordinal = 0, type = PrimaryKeyType.PARTITIONED, ordering = Ordering.ASCENDING)
    @Id
    private String uniqueId;

    /*Other details*/
}

回答1:

Yes, it is possible if you have the correct repository configurations. For specific details, please see the documentation.



回答2:

Yes it is very much possible. One classic example is when you want to have different datasources in your local/test and production environments. You could use Mongo in your test environment and MySql in production. So you could use both spring-data-mongo and javax.persistance annotations simultaneosly