JPA is mostly similar in use but there are a few gotchas.
One that got me the other day was what happens when you write a query that you expect to return a single result.
In Hibernate I’d have called
The Javadoc for that method says:
Convenience method to return a single instance that matches the query, or null if the query returns no results.
So, the query either returns my object or null (an exception is thrown if my query returns more than one result – fair enough).
I had to do something similar in JPA-land so I looked at its Query class.
It offered a similarly named method:
All good, I wrote my code, compiled it and restarted my application server.
Unfortunately, when I ran the code, it fell over with a
For my particular query, there were no results in our test database.
Fine, my code can deal with that, but clearly the JPA method works quite differently from the Hibernate version.
Its Javadoc says:
Execute a SELECT query that returns a single result.
NoResultException – if there is no result
So, unlike the Hibernate version this one will throw an exception if the query returns no results.
Hmmmm, I think I prefer the Hibernate version.
Of course, if it had thrown a checked exception my code would not have even compiled.
As it was it was just luck that the database had no results so I found the problem right away.
I’m not saying unchecked exceptions are bad, on the whole I prefer them.
But there’s a certain element of retraining your brain to no longer rely on the compiler to tell you that you’re dealing with all possible error conditions.
I know, I know, there wouldn’t be a problem if I’d read the Javadoc up front, but how many people can honestly say that they read the Javadoc for every new method the first time that they call it?