【发布时间】:2018-04-03 08:15:24
【问题描述】:
我想使用 Spring Data Mongo 存储库并在运行时指定文档的集合。 我在这张票DATAMONGO-525 中找到了实现它的方法以及我做了什么:
使用 ThreadLocal 变量创建 GenericObject 和链接集合名称 这个静态变量:
@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();
}
}
我为 GenericObject 创建了 GenericRepository:
public interface GenericObjectRepository extends MongoRepository<GenericObject, ObjectId> {
}
所以,现在当我想从特定集合中获取/保存/删除 GenericObject 时,我应该在每个请求之前指定集合:
// 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));
问题是:
我的方法是线程安全的吗?有什么我看不到的问题吗?
SpringDataMongoDB 版本:2.0.5.RELEASE
【问题讨论】:
-
@OliverGierke,DATAMONGO-525 是最新版本吗?谢谢
标签: java mongodb spring-boot spring-data spring-data-mongodb