Reputation: 337
I am trying to reuse my existing EmployeeRepository code (see below) in two different microservices to store data in two different collections (in the same database).
@Document(collection = "employee")
public interface EmployeeRepository extends MongoRepository<Employee, String>
Is it possible to modify @Document(collection = "employee")
to accept runtime parameters? For e.g. something like @Document(collection = ${COLLECTION_NAME})
.
Would you recommend this approach or should I create a new Repository?
Upvotes: 9
Views: 11151
Reputation: 3979
I used @environment.getProperty()
to read from my application.yml
. Like so :
application.yml:
mongodb:
collections:
dwr-suffix: dwr
Model:
@Document("Log-#{@environment.getProperty('mongodb.collections.dwr-suffix')}")
public class Log {
@Id
String logId;
...
Upvotes: 4
Reputation: 991
This is a really old thread, but I will add some better information here in case someone else finds this discussion, because things are a bit more flexible than what the accepted answer claims.
You can use an expression for the collection name because spel is an acceptable way to resolve the collection name. For example, if you have a property in your application.properties file like this:
mongo.collection.name = my_docs
And if you create a spring bean for this property in your configuration class like this:
@Bean("myDocumentCollection")
public String mongoCollectionName(@Value("${mongo.collection.name}") final String collectionName) {
return collectionName
}
Then you can use that as the collection name for a persistence document model like this:
@Document(collection = "#{@myDocumentCollection}")
public class SomeModel {
@Id
private String id;
// other members and accessors/mutators
// omitted for brevity
}
Upvotes: 6
Reputation: 5379
It shouldn't be possible, the documentation states that the collection field should be collection name, therefore not an expression: http://docs.spring.io/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/core/mapping/Document.html
As far as your other question is concerned - even if passing an expression was possible, I would recommend creating a new repository class - code duplication would not be bad and also your microservices may need to perform different queries and the single repository class approach would force you to keep query methods for all microservices within the same interface, which isn't very clean.
Take a look at this video, they list some very interesting approaches: http://www.infoq.com/presentations/Micro-Services
Upvotes: 1