MySQL's LPAD String Function in JPA Query?

谁说胖子不能爱 提交于 2020-05-15 09:57:11

问题


May I know how to convert the following MySQL SQL to JPA query?

SELECT * FROM ORDER
WHERE LPAD(BATCH, 2, ' ') < LPAD('X', 2, ' ') ;

What I couldn't figure out is the LPAD() string function in JPA.

Do you have any idea?


回答1:


I know that is a very old post, but i am always be questioned by some colleagues when they are building JPA queries how to do the same thing. Almost never you will find a perfect fit function to do what do you want. But, using some logic you can get the same result, in full JPA.

A example of LPAD.

Expression<String> numberWithZeroLeft = builder.concat("0000", root.get("myNumber")); //Return something like 000012
Expression<Integer> expressionLength = builder.length(numberWithZeroLeft);
Expression<String> numberLpad = builder.substring(numberWithZeroLeft, e.builder.sum(expressionLength, -3), e.builder.literal(4)); //Return something like 0012

query.select(numberLpad);

Think in something like:

I have a string X, and need a string formatted in 4 zeros.
So we will get 0000 + X => "0000X"
And now just get the 4 last characters using substring.

I hope that help someone.

Cheers. =]




回答2:


In EclipseLink 2.1 there is a function FUNC for calling database specific functions, for example:

FUNC('LPAD', BATCH, 2, ' ') < FUNC('LPAD', 'X', 2, ' ')

From EclipseLink 2.4 and JPA 2.1 there is FUNCTION operator with the same functionality



来源:https://stackoverflow.com/questions/16040562/mysqls-lpad-string-function-in-jpa-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!