我的存储库中有以下方法:
@Query("{$and:[" +
"{$or:[{$where: '(?0) == null'} , {'unidadNegocio': {$regex: '^(?!?0$)', $options: 'i'}}]}," +
"{$or:[{$where: '(?1) == null'} , {'unidadNegocio': {$regex: '^?1$', $options: 'i'}}]},"+
"{$or:[{$where: '(?2) == null'} , {'cif_proveedor': {$regex: '^?2', $options: 'i'}}]},"+
"{$or:[{$where: '(?3) == null'} , {'referencia': ?3}]},"+
"{$or:[{$where: '(?4) == null'} , {'descripcion': {$regex: ?4, $options: 'i'}}]},"+
"{$or:[{$where: '(?5) == null'} , {'categoria.categoria': {$regex: ?5, $options: 'i'}}]}"+
"]}")
List<Articulo> findAllWithFilter(String me, String nombre_proveedor, String cif_proveedor, Integer codigo, String desc,
String categoriaArticulo);
如您所见,我需要使用regex
。但是,方法属性可以为null,这导致我得到以下错误:
"org.springframework.data.mongodb.UncategorizedMongoDbException: Query failed with error code 2 and error message '$regex has to be a string' on server localhost:27017; nested exception is com.mongodb.MongoQueryException: Query failed with error code 2 and error message '$regex has to be a string' on server localhost:27017"
我需要如果它只是null,它会忽略它或某种东西,并且不会给我该异常,我该如何使用现在的@Query
注释实现它?
这是一种使用某些字段进行过滤的方法,但是该方法中的某些字段可以为null,因为用户没有选择通过该值进行过滤。
谢谢。
答案 0 :(得分:0)
尝试使用SpEL,有点像这样(我在这里无法测试,但是您应该知道这个想法):
@Query("{$and:[" +
"{$or:[{$where: '(?0) == null'} , #{ me == null ? {} : {'unidadNegocio': {$regex: '^(?!' + me + '$)', $options: 'i'}} }]}," +
"{$or:[{$where: '(?1) == null'} , #{ nombre_proveedor == null ? {} : {'unidadNegocio': {$regex: '^' + nombre_proveedor + '$', $options: 'i'}} }]},"+
"{$or:[{$where: '(?2) == null'} , #{ cif_proveedor == null ? {} : {'cif_proveedor': {$regex: '^' + cif_proveedor, $options: 'i'}} }]},"+
"{$or:[{$where: '(?3) == null'} , #{ codigo == null ? {} : {'referencia': codigo} }]},"+
"{$or:[{$where: '(?4) == null'} , #{ desc == null ? {} : {'descripcion': {$regex: desc, $options: 'i'}} }]},"+
"{$or:[{$where: '(?5) == null'} , #{ categoriaArticulo == null ? {} : {'categoria.categoria': {$regex: categoriaArticulo, $options: 'i'}} }]}"+
"]}")
List<Articulo> findAllWithFilter(String me, String nombre_proveedor, String cif_proveedor, Integer codigo, String desc,
String categoriaArticulo);