Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Returns null when query.getSingleResult() is returned directly

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.

like image 478
nsfyn55 Avatar asked Nov 13 '22 10:11

nsfyn55


1 Answers

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.

like image 59
Yuriy Zubarev Avatar answered Nov 16 '22 04:11

Yuriy Zubarev