0

我们正在从一个小表“ACCESS_STATUS”中获取数据,如下图所示。

ID 名称 1 外部 2 内部

当我们使用下面的 JPA 代码时: 在特定场景中,当两个用户同时访问该表时,第一行的 Name 列被提取为 NULL。该字段被进一步使用,因此抛出空指针异常并且应用程序停止工作并且必须重新启动。

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

如果我使用如下本机查询,则不存在此问题:

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));

        }
    }

这是 JPA/Java EE 中的错误吗?这个问题的永久修复是什么?

4

1 回答 1

1

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.

于 2013-09-12T19:08:19.900 回答