I have some very basic SQLs where mainly the column(s) and the table are exchanged, e.g. as simple as:
Select :COLUMNS from :TABLE
The SQLs can have 1 or many columns and there is always 1 table. I used JPA just because we are on a Java EE 7 server. So the code to run the native queries looks as follows:
@PersistenceContext(unitName = "sample")
EntityManager entityManager;
public List<Result> getResults() {
return Stream.of("SELECT one FROM demo1",
"SELECT two, columns FROM demo2")
.map(entityManager::createNativeQuery)
.map(Query::getSingleResult)
.flatMap(result -> {
// is Object for the first...
// and Object[] for the second...
if (result instanceof Object[]) {
return Arrays.stream((Object[])result);
} else {
return Stream.of(result);
}
})
.map(Result::new)
.collect(Collectors.toList());
}
The problem that I have right now: if I use only one column I get an Object
directly and if I use several columns I get an Object[]
. Is there some property/setting to always get an Object[]
? I saw setHint(ResultType, Array)
could solve that problem, but it requires implementation specific hints.
The reason why I want an Object[]
in the first place: (besides the code being already ugly on that specific instanceof
) the result itself is only helpful if I still know the appropriate column for it. The code sample rather simplifies that, but as the SQL is dynamically created, the columns are also known and can therefore be reused. If there is some other resultset mapping that could be used for such a construct, I am all ears.
For now I just use the shown instanceof
-check, but I wondered whether there is something in the standard that maybe solves that issue already. Any hints on how to better solve that issue are welcome (without further dependency of course).
Note: I can not adapt the table(s) and the result really makes sense this way.