如何在Restrictions.like中使用List <String>参数

Shavkat Turakulov:

ListRestrictions.in方法中使用对象,现在必须在“ Restrictions.likeRestrictions.like不接收List参数”中使用这种情况我怎么解决这个问题?我的代码是底部的:

public void setPhones(Set<String> phones) {
    this.phones.addAll(phones);
    if (!this.phones.isEmpty()) {
        aliases.add(new QueryAlias("profile", "profile"));
        criterions.add(Restrictions.like("profile.phone", this.phones));
    }
}
豪尔赫·杜阿尔特:

更正我以前(现在已编辑)的答案

根据文档(https://docs.jboss.org/hibernate/orm/5.4/javadocs/org/hibernate/criterion/Restrictions.html),您似乎没有直接的方法。

您可以尝试迭代列表,然后为每个电话创建一个Restriction列表,然后将该列表转换为一个数组,以用作Restrictions.or

public void setPhones(Set<String> phones) {

    this.phones.addAll(phones);

    if (!this.phones.isEmpty()) {
        // Creates a list to store criterions
        List<Criterion> criterionsPhoneNumbers = new ArrayList<>();

        // For each number searched, it creates a criterion with a "Like Restriction" adding to criterionsPhoneNumbers List. 
        // Pay attention to match mode (in raw sql it'll be a "like" using %phoneNumber% - check the generated SQL by hibernate).
        // You can change this to suit your needs.
        for (String number : numbers) {
            aliases.add(new QueryAlias("profile", "profile"));
            criterionsPhoneNumbers.add( Restrictions.like("number", number, MatchMode.ANYWHERE)  ) ;
        }

        // Here criterionsPhoneNumbers is being converted to array then added to the criteria with "Or Restriction" 
        criteria.add(Restrictions.or( criterionsPhoneNumbers.toArray(new Criterion[restrictionsPhoneNumbers.size()]) ));
    }


}

我之前的回答是错误的,因为将每个电话号码添加为Restriction.like(仅)是不够的,并且在“ where”子句中使用逻辑“ and”将其转换为sql。因为我还没有测试,所以看不到错误。我已经实现了,然后看到了错误。
我很抱歉。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章