JPA2: Case-insensitive like matching anywhere

后端 未结 7 2021
梦毁少年i
梦毁少年i 2020-12-13 03:45

I have been using Hibernate Restrictions in JPA 1.0 ( Hibernate driver ). There is defined Restrictions.ilike(\"column\",\"keyword\", MatchMode.ANYWHERE) which

7条回答
  •  一生所求
    2020-12-13 04:26

    It may seem a little awkward at first, but it is type-safe. Building queries from strings isn't, so you notice errors at runtime instead of at compile time. You can make the queries more readable by using indentations or taking each step separately, instead of writing an entire WHERE clause in a single line.

    To make your query case-insensitive, convert both your keyword and the compared field to lower case:

    query.where(
        builder.or(
            builder.like(
                builder.lower(
                    root.get(
                        type.getDeclaredSingularAttribute("username", String.class)
                    )
                ), "%" + keyword.toLowerCase() + "%"
            ), 
            builder.like(
                builder.lower(
                    root.get(
                        type.getDeclaredSingularAttribute("firstname", String.class)
                    )
                ), "%" + keyword.toLowerCase() + "%"
            ), 
            builder.like(
                builder.lower(
                    root.get(
                        type.getDeclaredSingularAttribute("lastname", String.class)
                    )
                ), "%" + keyword.toLowerCase() + "%"
            )
        )
    );
    

提交回复
热议问题