我们计划使用 Spring Data Azure Cosmos DB v3。我看到我们扩展了 CosmosRepository 接口并实现了我们的存储库并应用了 @Query 注释
@Query(value = "select * from c where c.firstName = @firstName and c.lastName = @lastName")
List<User> getUsersByTitleAndValue(@Param("firstName") int firstName, @Param("lastName") String lastName);
但是我们需要动态生成@Query中使用的sql
例如
String sql = "Select * from some table t"
if(someCondition){
sql.append(" where t.name="+ nameVar);
}
如何在 Spring Data Azure Cosmos DB v3 中实现这一点?
你可以这样做:-
@Query(value = "select * from c where (@firstName=null or c.firstName=@firstName) and (@lastName=null or c.lastName=@lastName)")
List<User> getUsersByFirstNameAndLastName(@Param("firstName") String firstName, @Param("lastName") String lastName);
这样它将忽略null参数。
Spring Data Azure Cosmos DB 通过 Spring Data 框架的标准接口公开 Azure Cosmos DB SQL API。 Spring Data 框架不面向动态查询,因为没有直接的方法可以在保持 Spring Data 约定范围内的同时对底层数据存储执行任意查询字符串。这些来源提出了两种以编程方式构建动态查询或将它们定义为映射的方法:
https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/ http://shazsterblog.blogspot.com/2017/01/spring-data-jpa-with-dynamic-where.html
或者 - Spring Data Azure Cosmos DB 构建在用于 SQL API 的 Azure Cosmos DB Java SDK 之上,这是我们的本机 Java SDK:
https://learn.microsoft.com/en-us/azure/cosmos-db/sql-api-sdk-java-v4
您可以为我们的本机 SDK 引入 Java bean,并使用本机 SDK 进行动态查询。
您需要扩展
spring-data-cosmos
以按照 ReactiveCosmosTemplete
、CosmosTemplate
设计模式传回 CosmosClient
或 CosmosAsyncClient
(Template
或 Callback
也可以)。
使用
EntityManager
编写动态查询时传递 spring-data-jpa
的方式相同。
您可以在我的博客中找到更多详细信息:https://tech.asimio.net/2023/08/28/Writing-Dynamic-Azure-Cosmos-DB-Queries-Spring-Data-Cosmos-ReactiveCosmosTemplate.html
以下是您需要遵循的一些步骤:
ReactiveCosmosTemplete
公共接口ReactiveCosmosQueryCallback {
CorePublisher doWithReactiveCosmosTemplate(ReactiveCosmosTemplate cosmosTemplate);
}
@NoRepositoryBean 公共接口 AsimioReactiveCosmosRepository {
Flux findAll(ReactiveCosmosQueryCallback 回调);
}
公共类 AsimioReactiveCosmosRepositoryImpl
受保护的最终 ReactiveCosmosTemplate cosmosTemplate;
@覆盖 公共 Flux findAll(ReactiveCosmosQueryCallback 回调) { 返回(Flux)callback.doWithReactiveCosmosTemplate(this.cosmosTemplate); }
ReactiveCosmosRepository
和自定义 CosmosRepository 的存储库接口,以便该特定存储库可以实现回调接口。@存储库
公共接口 UserRepository 扩展了 ReactiveCosmosRepository
默认 Flux findAll(UserSearchCriteria searchCriteria) { 返回 this.findAll(new ReactiveCosmosQueryCallback() {
@Override
public Flux<User> doWithReactiveCosmosTemplate(ReactiveCosmosTemplate cosmosTemplate) {
Map<String, Object> queryParams = this.buildQueryParameters();
//这里写动态查询
由于某种原因,使用
blockquotes
或 block samples
按钮 无法按预期进行格式设置
介绍了这种方法