I have a very simple Groovy class where I’m just trying to select a String from an Oracle 11g database using a native SQL query through Hibernate 3.3.2 GA. It seems so simple and yet I can’t make sense of the results I’m getting. Here is the code:
package serialize
import org.hibernate.cfg.Configuration
import org.hibernate.transform.ToListResultTransformer
class SerializeDatabaseObjects {
static main(args) {
def sessionFactory = initHibernate()
def session = sessionFactory.openSession()
def tx
def result
try {
tx = session.beginTransaction()
result = session
.createSQLQuery("""Select 'Hello World!' from dual""")
.setResultTransformer(ToListResultTransformer.INSTANCE)
.list()
tx.commit()
}
catch (Exception e) {
if (tx!=null){
tx.rollback()
}
throw e
}
finally {
session.close()
}
println result
sessionFactory.close()
}
static initHibernate(){
return new Configuration().configure().setProperty("hibernate.show_sql", "true").buildSessionFactory()
}
}
Output:
Hibernate: Select 'Hello World!' from dual
[[H]]
The ToListResultTransformer was my latest attempt to get the entire 'Hello World!' String to get printed but IMO shouldn’t be needed. But no matter what I try ‘H’ is always the result.
How do I get the entire ‘Hello World’ string to be returned?
As I was typing this question I figured out the answer. It appears that Hibernate is interpreting the result as a character instead of a String and therefore only returning ‘H’.
The way I found to fix this is to add a column alias in the select statement and then use addScalar(String columnAlias, Type type) to specify that the result should be interpreted as a String.
Again, I used a ResultTransformer(AliasToEntityMapResultTransformer) so my result would contain the column name and it’s contents but it is not strictly necessary.
If anyone would like to expand on why Hibernate is mapping the result as a character instead of a String or suggest an alternative(easier) way of forcing the result to be a string, please comment or post an answer.
Here is the code that produces the expected results:
And the output: