简体   繁体   中英

Can we do left padding to a JPA criteria expression?

I have a primary key column like colId which has values like 70 71 etc.

Now I want to have a JPA Criteria expression to return it like 0070 0071 etc.

How can we do that in JPA Criteria Expression.

Expression<String> colId = root.get("colId").as(String.class);

Now is there anything to leftpad this expression?

You could use the criteria builder 'function' expression which creates an expression to execute a database function. Postgres and MySQL have an 'LPAD' function which could be used in this case. I am still setting up a test case for this, but I have the following:

Expression<String>[] args = new Expression[3];

args[0] = root.get("id_column_name").as(String.class);
args[1] = criteriaBuilder.literal("5");
args[2] = criteriaBuilder.literal("0");

Expression<String> expressionToGetPaddedId = 
    criteriaBuilder.function("LPAD", String.class, args);

For reference:


Update:

Using a quick test case, I found that my second argument was incorrectly typed. Here is the 'toPredicate' overridden method from my spec:

    @Override
    public Predicate toPredicate(@NonNull Root<T> root,
                                 @NonNull CriteriaQuery<?> criteriaQuery,
                                 @NonNull CriteriaBuilder criteriaBuilder) {


        Expression<String> eTaskID = root.get("id").as(String.class);
        Expression<Integer> length = criteriaBuilder.literal(4);
        Expression<String> fillText = criteriaBuilder.literal("0");

        Expression<String> expressionToGetPaddedId = criteriaBuilder.function(
                "LPAD",
                String.class,
                eTaskID, length, fillText);

        return criteriaBuilder.like(expressionToGetPaddedId, "0001");
    }

and the resulting sql is:

Hibernate: 
    select
        dataset0_.id as id1_2_,
        dataset0_.created_at as created_2_2_,
        dataset0_.is_deleted as is_delet3_2_,
        dataset0_.model as model4_2_,
        dataset0_.name as name5_2_,
        dataset0_.organization as organiza6_2_,
        dataset0_.properties as properti7_2_,
        dataset0_.type as type8_2_,
        dataset0_.updated_at as updated_9_2_ 
    from
        datasets dataset0_ 
    where
        LPAD(cast(dataset0_.id as varchar(255)), 4, ?) like ?

The test case runs fine. Looks good, right?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM