I wanted to use Spring Data Mongo repositories and specify collection of the document at runtime. I found the way how I can achieve it in this ticket DATAMONGO-525 and what I did:
Created GenericObject with ThreadLocal variable and linked collection name with this static variable:
@Data
@Document(collection = "#{T(com.test.myproject.model.GenericObject).getCollection()}")
public class GenericObject {
private static ThreadLocal<String> collection = new ThreadLocal<>();
@Id
private ObjectId id;
private org.bson.Document doc;
public static void setCollection(String type) {
collection.set(type);
}
public static String getCollection() {
return collection.get();
}
}
I created GenericRepository for GenericObject:
public interface GenericObjectRepository extends MongoRepository<GenericObject, ObjectId> {
}
So, now when I want to get/save/delete GenericObject from specific collection I should specify collection before each request:
// save
GenericObject obj = new GenericObject();
GenericObject.setCollection(collectionName);
genericObjectRepository.save(obj)
...
//get
GenericObject.setCollection(collectionName);
genericObjectRepository.findById(new ObjectId(id))
.orElseThrow(() -> new RecordNotFoundException("GOS00001", id, collection));
The question is:
Is my approach is thread safe? Are there any issues that I don't see?
SpringDataMongoDB version: 2.0.5.RELEASE