2

我有以下实体类(继承自 PersistentObjectSupport 类的 ID):

@Entity
public class AmbulanceDeactivation extends PersistentObjectSupport implements Serializable {
    private static final long serialVersionUID = 1L;

    @Temporal(TemporalType.DATE) @NotNull
    private Date beginDate;

    @Temporal(TemporalType.DATE)
    private Date endDate;

    @Size(max = 250)
    private String reason;

    @ManyToOne @NotNull
    private Ambulance ambulance;

    /* Get/set methods, etc. */
}

如果我使用 Criteria API 执行以下查询:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AmbulanceDeactivation> cq = cb.createQuery(AmbulanceDeactivation.class);
Root<AmbulanceDeactivation> root = cq.from(AmbulanceDeactivation.class);
EntityType<AmbulanceDeactivation> model = root.getModel();
cq.where(cb.isNull(root.get(model.getSingularAttribute("endDate", Date.class))));
return em.createQuery(cq).getResultList();

我在日志中打印了以下 SQL:

FINE: SELECT ID, REASON, ENDDATE, UUID, BEGINDATE, VERSION, AMBULANCE_ID FROM AMBULANCEDEACTIVATION WHERE (ENDDATE IS NULL)

但是,如果我将前面代码中的 where() 行更改为这一行:

cq.where(cb.isNull(root.get(model.getSingularAttribute("endDate", Date.class))),
    cb.equal(root.get(model.getSingularAttribute("ambulance", Ambulance.class)), ambulance));

我得到以下 SQL:

FINE: SELECT ID, REASON, ENDDATE, UUID, BEGINDATE, VERSION, AMBULANCE_ID FROM AMBULANCEDEACTIVATION WHERE (AMBULANCE_ID = ?)

也就是说,完全忽略 isNull 标准。就好像它甚至不存在(如果我只提供与 where() 方法相同的标准,我会得到相同的 SQL 打印)。

这是为什么?这是一个错误还是我错过了什么?

4

2 回答 2

2

我使用 EclipseLink 测试了您的代码和条件查询(您正在使用 EclipseLink,对吗?),我重现了该行为:该isNull部分被忽略了。

但是,使用 Hibernate Entity Manager 3.5.1,会生成以下查询:

select ambulanced0_.id as id7_, ambulanced0_.ambulance_id as ambulance5_7_, ambulanced0_.beginDate as beginDate7_, ambulanced0_.endDate as endDate7_, ambulanced0_.reason as reason7_ 
from AmbulanceDeactivation ambulanced0_ 
where (ambulanced0_.endDate is null) and ambulanced0_.ambulance_id=?

这是预期的结果。所以我想我们可以假设这是您的 JPA 2.0 提供程序的错误。

于 2010-06-10T23:06:10.877 回答
1

我在使用嵌入了 EclipseLink 2.0 的 Glassfish 3.0.1 时遇到了同样奇怪的行为。

我曾尝试使用 Glassfish 3.1.2 中包含的 Eclipselink 2.3 库仔细更改嵌入式 eclipselink 库。它解决了这个问题。所以可以肯定的是,相等条件下的 isNull 检查是一个使用标准构建器的 eclipselink 错误。

我将尽快升级我们的 GlassFish 环境以消除该问题。

于 2013-02-08T19:26:00.990 回答