简体   繁体   中英

Challenge with getting correct mappings for aliases using Java+Hibernate+DB2

I am writing a Java application using Hibernate and IBM DB2 9.7 LUW for database. I am using the SQLQuery API to read a custom SQL query string and execute it against the DB. The query contains aliases, ie SELECT WORK.EMPLOYEE AS WORKEMPLOYEE , just as an example.

When retrieving the result set from DB with list() command, the resulting map does not contain the alias as key. So writing map.containsKey("WORKEMPLOYEE") returns false . I also tried using query.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE) but it did not change the situation.

I don't know Hibernate, but I suspect this is a symptom of an issue we've seen regarding DB2 LUW and aliases.

It relates to the distinction between a column's "name" and its "label". IBM document the behaviour at this page , which suggests that the behaviour will be different with different versions of the database driver.

Specifically, this paragraph:

Whether a column in the SELECT list of a query has an AS clause. For JDBC drivers before the IBM Data Server Driver for JDBC and SQLJ Version 4.0, if a column in the SELECT list of a query contains an AS clause,ResultSetMetaData.getColumnNamereturns the argument of the AS clause. Under the IBM Data Server Driver for JDBC and SQLJ Version 4.0,ResultSetMetaData.getColumnNamereturns the table column name.

suggests that you are seeing the behaviour that you (and I) regard as faulty because you are using a version 4+ driver.

There are three possible solutions, none of which is entirely satisfactory.

  1. Use a version 3.x driver.
  2. You can switch to calling getColumnLabel on the ResultSetMetaData . That would give you the correct result with DB2 LUW using version 4+ drivers. This applies to our version of the problem, but might not be relevant or possible via Hibernate.
  3. There is a property which you can set on the DataSource or Connection object: useJDBC4ColumnNameAndLabelSemantics would need to be set to DB2BaseDataSource.NO . However, I don't know whether you can set that via Hibernate. If you can, it should make aliases behave the old (and propert) way.

In our environment we haven't decided yet on how best to deal with this. We're working around it using option 1 for the moment. I'm inclined to use option 2, but we have to suport multiple DB platforms, and I'm not sure how it will work with the others. For option 3, we're sing Spring, so it may not be practical to set that property.

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