Saturday, January 5, 2008

Data Conversion Functions in JPQL?

So it appears that there is no equivalent to TO_NUMBER in JPQL which is causing a bit of an inconvenience when trying to query based on numeric criteria on a character column. I don't want to fall back on an Oracle native query.

I need a work-around which will be embedded within a JPQL criteria creation class.

JPQL does provide:

concat(str1, str2)
substring(str, start, length)
length(str)
trim(str)

Using these function it should be possible to produce a workable query.

If this is the query that I want to write:

select a
from ClassA a
where to_number(a.val) > 10 and to_number(a.val) < 300


My work-around could look as follows:

select a
from ClassA a
where substring(concat('000000000000000',trim(a.val)),length(trim(a.val),16)
> '0000000000000010'
and substring(concat('000000000000000',trim(a.val)),length(trim(a.val),16)
< '0000000000000300'


This works because it forces leading zeros in front of the numerical value, forcing the length of the value to 16 digits. The number 16 was arbitrarily chosen. It provides more than enough digits for my purposes, but could be extended if necessary.

The verbosity of the query looks unwieldy, but in reality the query will be auto generated.

There is likely to be a performance hit. The database will have to make several function calls for every evaluation.

No comments: