【问题标题】:JPA EclipseLink getCount of child entity子实体的 JPA EclipseLink getCount
【发布时间】:2012-05-22 20:45:50
【问题描述】:

我正在使用 EL,当我运行下面的查询时,我一直得到 0。我想获取当前处于活动状态的申请人 (AP) 的数量。子实体申请人属于 Person,我想避免查询 Person 的所有元素?

@RooJavaBean
@RooToString
@RooEntity(identifierColumn = "personID", inheritanceType = "SINGLE_TABLE")
@DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.STRING, length = 20)
@DiscriminatorValue("P")
public class Person {

    @NotNull
    @Size(min = 1, max = 50)
    private String FirstName;

    @NotNull
    @Size(min = 1, max = 50)
    private String LastName;
}

子实体“申请人”

@RooJavaBean
@RooToString
@RooEntity
@DiscriminatorValue("AP")
public class Applicant extends Person{

    private String major;

    private String nativeLanguage;

    private String ethnicity;

    private String hispanic;
}

我的查询尝试:

   /**
     * 
     * @return
     */
    public int getCountActiveApplicants(){

        EntityManager entityManager = factory.createEntityManager();
        int value = entityManager.createQuery("select count(distinct o) from Person o where o.TYPE = \"AP\" AND o.active = \"Yes\" ").getFirstResult();

        System.out.println("wowzer " + value + "\n");
        return value;
    }

【问题讨论】:

    标签: jpa entity eclipselink createquery


    【解决方案1】:

    你为什么不简单地计算申请人数?

    select count(distinct a) from Applicant a where a.active = true
    

    EclipseLink 将在 SQL 中对其进行转换,并为您在鉴别器上添加 where 子句。 请记住,JPQL 与您的实体及其持久字段/属性一起使用。它知道它们的关联和它们的继承层次结构。 JPQL 从不使用表名和列名。

    (旁注:为什么对布尔字段使用“是”?)

    【讨论】:

    • 它实际上不是一个布尔字段,我想将其设置为“是”或“否”,但当我可以使用 true 或 false 时,它​​可能不是一件好事。我现在就试试上面的这个查询。谢谢
    • 要从这个实体管理器获取计数,我应该使用 getFirstResult() 吗?
    • 没有。您应该使用 getSingleResult():docs.oracle.com/javaee/6/api/javax/persistence/…。 getFirstResult() 返回由 setFirstResult() 设置的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多