JPA EclipseLink getCount de entidad secundaria

I am using EL and i keep getting 0 when i run the query below. I want to get the count of applicants (AP) that are currently active. The child entity Applicant is of Person and i want to avoid querying all elements of 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;
}

The child entity 'Applicant'

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

    private String major;

    private String nativeLanguage;

    private String ethnicity;

    private String hispanic;
}

My query attempt:

   /**
     * 
     * @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;
    }

preguntado el 22 de mayo de 12 a las 21:05

1 Respuestas

Why don't you simply count the applicants?

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

EclipseLink will transform this in SQL and add the where clause on the discriminator for you. Remember that JPQL works with your entities and their persistent fields/properties. It knows about their association and their inheritance hierarchy. JPQL never uses table and column names.

(Side note: why use "Yes" for a boolean field?)

contestado el 22 de mayo de 12 a las 22:05

Its actually not a boolean field i wanted to set it to 'Yes' or 'No' but its probably not a good thing when i can use true or false. I will try this query above right now. Thanks - Guerraz

to get the count from this entity manager, am i supposed to use getFirstResult()? - Guerraz

No. You're supposed to use getSingleResult(): docs.oracle.com/javaee/6/api/javax/persistencia/…. getFirstResult() returns what was set by setFirstResult(). - JB Nizet

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.