2

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

Andrew Nepogoda
  • 1,825
  • 17
  • 24

1 Answers1

0

Sounds like you're almost better off just using MongoOperations directly. Why bother with worrying with ThreadLocal. If you want to see more info about static ThreadLocal usage you can refer to this question: Java ThreadLocal static? But yeah you're approach is fine. ThreadLocal is safe to use as a different thread can't set ThreadLocal of another thread.

Strelok
  • 50,229
  • 9
  • 102
  • 115
  • Thanks for answer @Strelok, The challenge was to use MongoRepositories without implementing CRUD operations with MongoTemplate or MongoOperations. And I just wanna be sure that there won't be any side effects from spring. – Andrew Nepogoda Apr 03 '18 at 15:22