Databases don’t have Long as a data type. Because of it Hibernate have to convert java.lang.Long
Java type into database type (e.g. BIGINT
) before persistence. For this reason
Hibernate cannot recognise Long as a result of a database query which returns a numeric result, such as range of IDs.
If you expect from the bellow query
Java
long results then Hibernate will throw an exception
Changing expected result type in resultClass
to BigInteger
doesn’t help as now Hibernate reports unknown entity as java.math.BigInteger
.
Note: Adding java.lang.Long to persistence.xml doesnt work, I have tried it :).
ResultSetMapping for the rescue
The fix is to create @SqlResultSetMapping
declaration with the name of the column to be mapped. Next, add resultSetMapping
parameter to the Named Query declaration. Just make sure its value matches the name parameter in the @SqlResultSetMapping
annotation.
Java
Still, the result of the query will be of BigInteger
type, but this can be easy converted.
Java
Conclusion
Object-relational Mapping (ORM) promises an easier life for software developers. Especially for those who has little experience with databases. But there are many quirks like this which makes me scratching my head with loud “What?! Why?”.