1
person:

id | owner_email               | firstname | lastname 
----+-------------+-----------+----------
 44 | john@gmail.com           | john       | wood
 45 | alex@gamil.com           | alex       | greenwood
 49 | peter@gamil.com          | peter      | blacksmith
 50 | john@gmail.com           | lee        | wu
 51 | john@gmail.com           | jane       | li

i am making a spring hibernate web application, i have a table like above. what i m trying to get is something like:

select * from person where owner_email='john@gmail.com'

so the method will return me list of person objects related to john@gmail.com

here is my query code but doesnt work...

    @PersistenceContext
    EntityManager em;


    @Transactional
    public List<Person> listPerson() {
        CriteriaQuery<Person> c = em.getCriteriaBuilder().createQuery(Person.class);
        Root<Person> from = c.from(Person.class);
        c.multiselect(from.get("owner_email"));
        c.orderBy(em.getCriteriaBuilder().asc(from.get("firstname")));
        return em.createQuery(c).getResultList();
    }

here is the error i get....

HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException: Unable to locate appropriate constructor on class [com.example.model.Person] [select new com.example.model.Person(generatedAlias0.owner_email) from com.example.model.Person as generatedAlias0]

please help me with code example thanks...

4

1 回答 1

4
@PersistenceContext 
EntityManager em;

@Transactional 
public List<Person> listPerson() { 
    CriteriaQuery<Person> c = em.getCriteriaBuilder().createQuery(Person.class); 
    Root<Person> from = c.from(Person.class); 

    c.select(from);
    c.where(em.getCriteriaBuilder().equal(from.get("owner_email"),"john@gmail.com")); // <- this will add the restriction. 

    c.orderBy(em.getCriteriaBuilder().asc(from.get("firstname"))); 
    return em.createQuery(c).getResultList(); 
}
于 2014-08-10T22:34:50.060 回答