2

我想打印出Person所有isFoo == true. 我不知道如何完成以下代码PersonServlet

@Entity
public class Person implements Serializable {

    @Id
    @GeneratedValue
    private Long id;
    private Boolean foo;
    private Boolean fooBar;

    public Person() {
    }

    public Person(Boolean foo, Boolean fooBar) {
        this.foo = foo;
        this.fooBar = fooBar;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Boolean getFoo() {
        return foo;
    }

    public void setFoo(Boolean foo) {
        this.foo = foo;
    }

    public Boolean getFooBar() {
        return fooBar;
    }

    public void setFooBar(Boolean fooBar) {
        this.fooBar = fooBar;
    }

}

PersonServlet

public void printAllFoo() {
    EntityManagerFactory emf = (EntityManagerFactory) getServletContext().getAttribute("emf");
    EntityManager em = emf.createEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery q = cb.createQuery(Person.class);
    Root<Person> c = q.from(Person.class);
    q.select(c);
    ParameterExpression<Boolean> foo = cb.parameter(Boolean.class); //Should this be = true instead?
    ParameterExpression<Boolean> fooBar = cb.parameter(Boolean.class); //Should this be = false instead?
    q.where(
            cb.equal(c.get("foo"), cb.literal(true)),
            cb.equal(c.get("fooBar"), cb.literal(true))
    );
    TypedQuery<Person> query = em.createQuery(q);
    query.setParameter(foo, true);
    query.setParameter(fooBar, false);
    List<Person> fooPersons = query.getResultList();
    System.out.println("fooPersons: " + fooPersons);
}

目前打印出来的是:

fooPersons: []

即使数据库中有很多条目:

web.application.bean.Person@50d420eb
web.application.bean.Person@16bd4dc2
web.application.bean.Person@663c0737
web.application.bean.Person@6efde050
web.application.bean.Person@5d91dd1d
web.application.bean.Person@134bcae9
web.application.bean.Person@54f690e4
web.application.bean.Person@7a29450
web.application.bean.Person@42b7141a
web.application.bean.Person@188d92e
web.application.bean.Person@3f6a5bcb
web.application.bean.Person@5fb08cf3
web.application.bean.Person@3ff5d699
web.application.bean.Person@24dbf79d
web.application.bean.Person@655d7752
4

1 回答 1

1

尝试:

  TypedQuery<Person> query = em.createQuery(q);
  query.setParameter(foo, true);
  query.setParameter(fooBar, false);
  List<Person> fooPersons = query.getResultList();

参数可以用文字替换,例如:

  cb.equal(c.get("isFoo"), cb.literal(true));
于 2014-10-17T16:39:30.397 回答