问题
This question is a spin-off from ANY operator with jOOQ and Are arrays optimized in jOOQ & PostgreSQL?.
I have a Field<T> field
and List<T> values
and I want to express SQL identifier = any({... the values ...})
. I tried doing:
field.equal(DSL.any(DSL.val(values.stream().toArray())))
(Note this is part of a generic implementation, so I don't have the actual types at this point. I only have Field<T>
and List<T>
.)
But this doesn't work, since the API accepts T...
instead of Object...
and field.equal(DSL.any(...))
needs that T
. So, I changed this to:
field.equal(DSL.any(DSL.val((T[]) values.stream().toArray())))
However, in comments is said that I should not do this. Probably a dumb question and Java instead of jOOQ question, but how should it be done?
Side question: isn't it a good idea to simply accept a List<T>
in the API? This might also improve performance, since we are avoiding the manual array creation.
Note: The same situation holds for field.equal(DSL.any(values.stream().toArray()))
and field.equal(DSL.any(DSL.array(values.stream().toArray())))
.
回答1:
Every time you're using the jOOQ API with an unsafe cast, you should wonder: Am I using it right?
In your case the mistake is here:
DSL.val((T[]) values.stream().toArray())
The correct way to construct this array is (assuming T
is Integer
, here):
DSL.val(values.stream().toArray(Integer[]::new))
Or, if values
is a Collection
, then more simply:
DSL.val(values.toArray(new Integer[0]))
It is important that you pass an array of the correct type to jOOQ as jOOQ will use reflection on that array to figure out what data type it is, and then map it to e.g. PostgreSQL ?::int[]
Side question: isn't it a good idea to simply accept a
List<T>
in the API? This might also improve performance, since we are avoiding the manual array creation.
The problem is that Java erases the generic type information of T
, which jOOQ needs to correctly cast bind variables in various edge case situations. So, T[]
is a much more preferrable type than List<T>
in such cases.
来源:https://stackoverflow.com/questions/45858042/jooq-fieldt-dsl-anydsl-valt