import org.springframework.web.bind.annotation.*; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; @RestController @RequestMapping("/api/person") public class PersonController { @Autowired private PersonService personService; @GetMapping("/search") public List<YourEntityClass> search( @RequestParam String keyword, @RequestParam String value) { // 调用 Service 查询方法 return personService.searchByKeyword(keyword, value); } } import org.springframework.stereotype.Service; import java.util.List; @Service public class PersonService { @Autowired private YourEntityClassMapper yourEsMapper; private final QueryStrategyFactory<YourEntityClass> strategyFactory = new QueryStrategyFactory<>(); public List<YourEntityClass> searchByKeyword(String keyword, String value) { EsQueryBuilder<YourEntityClass> builder = new EsQueryBuilder<>(YourEntityClass.class); // 获取通用查询策略 QueryStrategy<YourEntityClass> strategy = strategyFactory.getStrategy(keyword); // 应用策略 strategy.apply(builder.getQueryWrapper(), value); // 执行查询 return yourEsMapper.selectList(builder.build()); } } import com.xpc.easyes.core.conditions.LambdaEsQueryWrapper; public class FieldQueryStrategy<T> implements QueryStrategy<T> { private final String field; public FieldQueryStrategy(String field) { this.field = field; } @Override public void apply(LambdaEsQueryWrapper<T> queryWrapper, String value) { if (field.contains(".")) { // 如果字段是嵌套字段,例如 "list.name" String[] parts = field.split("\\."); String nestedPath = parts[0]; String nestedField = parts[1]; queryWrapper.nested(nestedPath, w -> w.eq(nestedPath + "." + nestedField, value)); } else { // 普通字段查询 queryWrapper.eq(field, value); } } } import java.util.HashMap; import java.util.Map; public class QueryStrategyFactory<T> { private final Map<String, QueryStrategy<T>> strategies = new HashMap<>(); public QueryStrategyFactory() { // 注册字段对应的通用策略 registerField("name"); registerField("list.name"); // 可以在此添加其他字段 } private void registerField(String field) { strategies.put(field, new FieldQueryStrategy<>(field)); } public QueryStrategy<T> getStrategy(String keyword) { QueryStrategy<T> strategy = strategies.get(keyword); if (strategy == null) { throw new IllegalArgumentException("Invalid keyword: " + keyword); } return strategy; } } import com.xpc.easyes.core.conditions.LambdaEsQueryWrapper; import com.xpc.easyes.core.core.EsWrappers; public class EsQueryBuilder<T> { private final LambdaEsQueryWrapper<T> queryWrapper; public EsQueryBuilder(Class<T> clazz) { this.queryWrapper = EsWrappers.lambdaQuery(clazz); } public LambdaEsQueryWrapper<T> getQueryWrapper() { return queryWrapper; } public LambdaEsQueryWrapper<T> build() { return queryWrapper; } } import com.xpc.easyes.core.conditions.LambdaEsQueryWrapper; public interface QueryStrategy<T> { void apply(LambdaEsQueryWrapper<T> queryWrapper, String value); }
标签:queryWrapper,LambdaEsQueryWrapper,String,field,test,import,public From: https://www.cnblogs.com/findlisa/p/18528899