2017-08-23 16 views
1

私は複数の属性でユーザーの検索を実装しようとしています。 私の人は名前と姓を持っているとしましょう。私は「マイケル・ドゥ」と入力し、この名前と姓の人をすべて一覧にしたいと思います。私が「マイケル」だけをタイプするとき、私はすべてのマイケルズがほしいと思う。Springデータ仕様 - 複数の属性でオブジェクトをフィルタリングするにはどうすればいいですか

私のような述語を使用することによって、それが可能に作ってみました:

private static Specification<UserEntity> containsTextInAttributes(List<String> text, List<String> attributes) { 
    List<String> finalTextArray = text.stream().map(e -> "%"+e+"%").collect(Collectors.toList()); 
    return (root, query, builder) -> builder.or(root.getModel().getDeclaredSingularAttributes().stream() 
      .filter(a -> attributes.contains(a.getName())) 
      .map(a -> builder.or(finalTextArray.stream().map(e -> builder.like(root.get(a.getName()), e)).toArray(Predicate[]::new))) 
      .toArray(Predicate[]::new) 
    ); 
} 

public static Specification<UserEntity> containsTextInAllAttributes(List<String> text) { 
    return containsTextInAttributes(text, Arrays.asList("lastname", "firstname", "email", "phoneNumber")); 
} 

しかし、私は、検索時に「マイケル・ドウ」私はどのように私は私の問題を解決することができ、すべてのマイケルズと姓がDoeですべてを持っている

。?

は助けを事前にいただきありがとうございます。

+0

この[リンク](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.named-parametersは)助けてもいいですか? – juanlumn

+0

データをフィルタリングするために複数の単語を使用したいからです。 –

+0

あなたを助けた\ upvoteの回答を受け入れることを忘れないでください... – Cepr0

答えて

0

I."Michael D", "firstName", "lastName"、または"[email protected]", "email"

public <T> Specification<T> dynamicLike(String likeValue, String... properties) { 
    return (Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> { 

     Expression<String> concat = null; 

     for (String property : properties) { 
      if (concat == null) { 
       concat = cb.concat("", root.get(property)); 
      } else { 
       concat = cb.concat(concat, cb.concat(" ", root.get(property))); 
      } 
     } 

     return cb.like(cb.lower(concat), "%" + likeValue.toLowerCase() + "%"); 
    }; 
} 

II。"Mic Do @gmail", "firstName", "lastName", "email"

public <T> Specification<T> dynamicLike2(String value, String... properties) { 
    return (Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> { 

     String[] values = value.split("\\s"); 
     int minNumber = Integer.min(values.length, properties.length); 

     Predicate[] likes = new Predicate[minNumber]; 

     for (int i = 0; i < minNumber; i++) { 
      likes[i] = cb.like(cb.lower(root.get(properties[i])), "%" + values[i].toLowerCase() + "%"); 
     } 

     return cb.and(likes); 
    }; 
} 
関連する問題