为JPQL BETWEEN语句添加条件

时间:2013-06-24 19:15:52

标签: java jpa jpql backend

我的实体类中有一个查询,并且正在使用JPA注释。我的BETWEEN语句返回结果,但我似乎无法标记此条件“WHERE e.feature =:feature”,它引用另一个表中的String值。

@Entity
@Table(name = "EVENTS")
public class Events implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long eventsPk;
    @ManyToOne
    @JoinColumn(name = "USERS")
    private Users user;
    @ManyToOne
    @JoinColumn(name = "FEATURES")
    private Features feature;
    @Column(name = "TIME_OF_ENTRY", unique = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date timeOfEntry;
...
}

在我的BusinessObject类中,我有这个查询,其中em是EntityManager实例:

public class EventsBusinessObject {
    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(EventsBusinessObject.class);
    public static List<Events> getEventsBetweenDates(EntityManager em, Date startDate, Date endDate, String feature) {
        List<Events> events = null;
        try {
            events = em.createQuery(
                    "SELECT e FROM Events e WHERE e.timeOfEntry 
                     BETWEEN :startDate AND :endDate 
                     AND SELECT Feature f FROM Features WHERE f.feature = :feature")
                    .setParameter("startDate", startDate, TemporalType.TIMESTAMP)
                    .setParameter("endDate", endDate, TemporalType.TIMESTAMP)
                    .setParameter("feature", feature)
                    .getResultList();
        } catch (NoResultException e) {
            logger.error("NoResultException for EventsBusinessObject.getEventsBetweenDates");
        } catch (Exception e) {
            logger.error("unknown exception for EventsBusinessObject.getEventsBetweenDates");
        }
        return events;
    }//end getEventsBetweenDates method

以下JPQL可以很好地返回条目:

SELECT e FROM Events e WHERE e.timeOfEntry BETWEEN :startDate AND :endDate

当我开始尝试添加Feature条件时,我没有从数据库中获得任何结果:

> @NamedQuery(name = "Events.getEventsBetweenDates", query = "SELECT e
> from Events e WHERE e.timeOfEntry BETWEEN :startDate AND :endDate" AND
> e.feature = :feature)

此查询是从BusinessObject查询方法调用时返回NullPointerException的查询:

SELECT e FROM Events e WHERE e.timeOfEntry BETWEEN :startDate AND :endDate AND e.feature = :feature

任何想法? 感谢

1 个答案:

答案 0 :(得分:0)

我突然意识到我可以利用Netbeans的自动完成功能来帮助我。在实体类中执行@NamedQuery()时,可以使用控件+空格键快捷方式让Netbeans告诉您哪些选项在语法上是正确的。

这是对我有用的查询:

    events = em.createQuery("SELECT e FROM Events e WHERE e.feature.name = :featureName AND e.timeOfEntry BETWEEN :startDate AND :endDate")
            .setParameter("startDate", startDate, TemporalType.TIMESTAMP)
            .setParameter("endDate", endDate, TemporalType.TIMESTAMP)
            .setParameter("featureName", featureName)
            .getResultList();