I have a very strange issue with hibernate and jpa. Below are two blocks of code:
public Object getObject(Date date) {
try {
Query query = entityManager
.createQuery(
"select ob from Object ob where date= :date");
query.setParameter("date", date);
return (Object)query.getSingleResult();
} catch (EmptyResultDataAccessException e) {
logger.debug(String.format("No Result found - date[%s]",date));
return null;
}
}
...
public Object getObject(Date date) {
try {
Query query = entityManager
.createQuery(
"select ob from Object ob where date= :date");
query.setParameter("date", date);
Object ret = (Object)query.getSingleResult();
return ret;
} catch (EmptyResultDataAccessException e) {
logger.debug(String.format("No Result found - date[%s]",date));
return null;
}
}
The first generates an EmptyResultDataAccessException every time even given a valid record where the date matches. The second returns a result as expected. Has anyone encountered this? What causes this behavior?
Please assume all other syntatical things are present(a transaction, initialized entitymanager, etc) the only thing that I change is whether the query results are retrieved directly in the return or assigned to a variable first.
It IS possible, I encountered it before as well. I think it has something to do with byte code manipulations that Hibernate is doing. To get to the root of it, you have to go to a very deep and dark level of implementation.
When working with Hibernate/JPA I always use the second pattern. It's unfortunate because it makes the code a bit more verbose, but it's not worth plunging into a depth of generated byte code and trying to comprehend it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With