Eclipse link JPA Select Query returns null field value

1.2k views Asked by At

We are fetching data from a small table 'ACCESS_STATUS' as depicted below.

ID NAME 1 External 2 Internal

When we use below JPA code: In a particular scenario, when two users simultaneously access this table, the Name column of the first row is fetched as NULL. This field is used further so a null pointer exception is thrown and the application stops working and it has to be restarted.

JpaEntityManager jpaEm = JpaHelper.getEntityManager(em);
ReadAllQuery query=new ReadAllQuery(AccessStatus.class);
 Collection accessStatus =  (Collection)jpaEm.getActiveSession().executeQuery(query)

If I use a native query like below, this problem is not there:

try {
preparedStatement=connection.prepareStatement(sb.toString());
resultSet=preparedStatement.executeQuery();

while (resultSet.next()) {
 id = resultSet.getString(1);
name = resultSet.getString(2);
accessStatus.add(new AccessStatus(id,name));

        }
    }

Is this a bug in JPA/Java EE? What is a permanent fix for this issue?

1

There are 1 answers

0
Chris On

This isn't strict JPA as you are accessing EclipseLink session to execute a native ReadAllQuery. Strict JPA would be

Collection accessStatus = em.createQuery("Select status from AccessStatus status").getResultList();

but it would likely give you the same result. The problem is likely not a JPA/EclipseLink/ORM bug, but in how your application is using the tools. First, the entity returned is going to be a managed entity, and reflect any changes you made within the session/context - even uncommited ones. So check that you are not somehow merging or persisting entities or otherwise populating entities that have a null name. A common error is for applications to create a new entity, and in setting up a relationship to an existing entity, instead of getting it with a find or getReference call, just create a new empty instance. This sets the foreign key, but you get what you put in, which will be missing data unless that object is refreshed.

You can verify this is occurring by calling em.refresh() on the AccessStatus returned from the query. If the name then is populated, you should track down how it is getting into the context with null values.