Dan*_*ish 24 java spring mongodb spring-data spring-data-mongodb
我有一个Products
在我的MongoDB数据库中调用的集合,它由IProductPrice
我的Java代码中的接口表示.以下存储库声明会导致Spring Date查看该集合db.collection: Intelliprice.iProductPrice
.
我希望它将其配置为db.collection: Intelliprice.Products
使用外部配置而不是放置@Collection(..)
注释IProductPrice
.这可能吗?我怎样才能做到这一点?
public interface ProductsRepository extends
MongoRepository<IProductPrice, String> {
}
Run Code Online (Sandbox Code Playgroud)
Jer*_*mie 12
使用上面的Oliver Gierke的答案,处理我需要为一个实体创建多个集合的项目,我想使用spring存储库,并且需要在使用存储库之前指定要使用的实体.
我设法使用此系统按需修改存储库集合名称,它使用SPeL.但是,您一次只能处理1个集合.
域对象
@Document(collection = "#{personRepository.getCollectionName()}")
public class Person{}
Run Code Online (Sandbox Code Playgroud)
默认Spring存储库:
public interface PersonRepository
extends MongoRepository<Person, String>, PersonRepositoryCustom{
}
Run Code Online (Sandbox Code Playgroud)
自定义存储库接口:
public interface PersonRepositoryCustom {
String getCollectionName();
void setCollectionName(String collectionName);
}
Run Code Online (Sandbox Code Playgroud)
执行:
public class PersonRepositoryImpl implements PersonRepositoryCustom {
private static String collectionName = "Person";
@Override
public String getCollectionName() {
return collectionName;
}
@Override
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
}
Run Code Online (Sandbox Code Playgroud)
要使用它:
@Autowired
PersonRepository personRepository;
public void testRetrievePeopleFrom2SeparateCollectionsWithSpringRepo(){
List<Person> people = new ArrayList<>();
personRepository.setCollectionName("collectionA");
people.addAll(personRepository.findAll());
personDocumentRepository.setCollectionName("collectionB");
people.addAll(personRepository.findAll());
Assert.assertEquals(4, people.size());
}
Run Code Online (Sandbox Code Playgroud)
否则,如果你需要使用配置变量,你可以使用这样的东西吗?资源
@Value("#{systemProperties['pop3.port'] ?: 25}")
Run Code Online (Sandbox Code Playgroud)
小智 5
有点晚了,但我发现您可以在 spring-boot 中动态设置 mongo 集合名称,直接访问应用程序配置。
@Document(collection = "#{@environment.getProperty('configuration.property.key')}")
public class DomainModel {...}
Run Code Online (Sandbox Code Playgroud)
我怀疑您可以通过这种方式设置任何注释属性。
归档时间: |
|
查看次数: |
27948 次 |
最近记录: |