如何解决在Spring Data Mongodb中使用Query类进行不区分大小写的排序
我正在使用这种排序方式,并且我希望不区分大小写。
dockerfile
我尝试了此查询,但没有得到任何结果。
使用的进口:
Query query = new Query();
query.with(new Sort(new Order(Sort.Direction.ASC,"title").ignoreCase()));
return db.find(query,Video.class);
例如,如果我有这种标题: “ Inception”,“ BlackList”,“ adore”,“ 123”,“ city”,“ desperadoS”
顺序应为: “ 123”,“ adore”,“ BlackList”,“ city”,“ desperadoS”,“ Inception”
如果我这样使用
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
返回
“ 123”,“ BlackList”,“ Inception”,“ adore”,“ city”,“ desperadoS”
Spring-data-mongodb版本1.9.2
解决方法
使用排序规则对忽略的案例进行排序。 例子是here
使用时,您将收到IllegalArgumentException
new Order(Sort.Direction.ASC,"title").ignoreCase())
在您的情况下:
Query query = new Query().with(Sort.by(new Sort.Order(Sort.Direction.ASC,"title")));
query.collation(Collation.of("en").strength(Collation.ComparisonLevel.secondary()));
return mongoTemplate.find(query,Video.class);
,
另一种将 Collation
与 @Query
注释结合使用以获得 "123","adore","BlackList","city","desperadoS","Inception"
的预期排序顺序的方法
文档
@Document(collection = "video")
@Data
public class Video {
@Id
private String id;
private String title;
public Video(String title) {
this.title = title;
}
}
存储库
@Repository
public interface VideoRepository extends MongoRepository<Video,String> {
@Query(collation = "en",value = "{}")
List<Video> getAllSortedVideos(Sort sort);
}
用于断言更改的集成测试类
@ActiveProfiles("test")
@SpringBootTest(classes = DemoApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class VideoRepositoryITest {
@Autowired
private VideoRepository videoRepository;
@Test
void getAllSortedVideos() {
List<String> expectedSystemNamesInOrder = Arrays.asList("123","Inception");
//breaking the order for fun
Set<String> expectedSystemNamesSet = new HashSet<>(expectedSystemNamesInOrder);
//saving the videos of each title
expectedSystemNamesSet.stream().map(Video::new)
.forEach(videoRepository::save);
//fetching sorted Videos by title
List<Video> videos = videoRepository.getAllSortedVideos(Sort.by(Direction.ASC,"title"));
//fetching sorted Video tiles to assert
List<String> titles = videos.stream().map(Video::getTitle).collect(Collectors.toList());
//asserting the result video title order with the expected order
for (int i = 0; i < titles.size(); i++) {
String actualTitle = titles.get(i);
String expectedTitle = expectedSystemNamesInOrder.get(i);
//Test case will fail if the retrieved title order doesn't match with expected order
Assertions.assertEquals(expectedTitle,actualTitle);
}
}
}
使用 org.springframework.data:spring-data-mongodb:3.0.4.RELEASE
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。