Creating queries using Criteria API (JPA 2.0)

Posted by Pym on Stack Overflow See other posts from Stack Overflow or by Pym
Published on 2010-04-08T19:22:11Z Indexed on 2010/04/08 19:23 UTC
Read the original article Hit count: 379

Filed under:
|
|

Hello there !

I'm trying to create a query with the Criteria API from JPA 2.0, but I can't make it work.

The problem is with the "between" conditionnal method. I read some documentation to know how I have to do it, but since I'm discovering JPA, I don't understand why it does not work.

First, I can't see "creationDate" which should appear when I write "Transaction_."

I thought it was maybe normal, since I read the metamodel was generated at runtime, so I tried to use 'Foo_.getDeclaredSingularAttribute("value")' instead of 'Foo_.value', but it still doesn't work at all.

Here is my code :

public List<Transaction> getTransactions(Date startDate, Date endDate) {
    EntityManager em = getEntityManager();
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Transaction> cq = cb.createQuery(Transaction.class);
        Metamodel m = em.getMetamodel();
        EntityType<Transaction> Transaction_ = m.entity(Transaction.class);
        Root<Transaction> transaction = cq.from(Transaction.class);

        // Error here. cannot find symbol. symbol: variable creationDate
        cq.where(cb.between(transaction.get(Transaction_.creationDate), startDate, endDate));

        // I also tried this:
        // cq.where(cb.between(Transaction_.getDeclaredSingularAttribute("creationDate"), startDate, endDate));

        List<Transaction> result = em.createQuery(cq).getResultList();
        return result;
    } finally {
        em.close();
    }
}

Can someone help me to figure this out? Thanks.

© Stack Overflow or respective owner

Related posts about java

Related posts about jpa