Hibernate Criteria Query select where子句

时间:2014-08-10 21:45:19

标签: java sql hibernate spring-mvc criteriaquery

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

我正在制作一个Spring hibernate Web应用程序, 我有一张像上面这样的桌子。 我想要得到的是:

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

所以该方法将返回与john@gmail.com相关的人物对象列表

这是我的查询代码但不起作用......

    @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();
    }

这是我得到的错误......

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]

请帮我解决代码示例谢谢......

1 个答案:

答案 0 :(得分:2)

@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(); 
}