0

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;
    }
Warz
  • 7,386
  • 14
  • 68
  • 120

1 Answers1

0

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

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 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 – Warz May 22 '12 at 21:09
  • to get the count from this entity manager, am i supposed to use getFirstResult()? – Warz May 22 '12 at 21:11
  • No. You're supposed to use getSingleResult(): http://docs.oracle.com/javaee/6/api/javax/persistence/Query.html#getSingleResult%28%29. getFirstResult() returns what was set by setFirstResult(). – JB Nizet May 22 '12 at 21:17