选择成员变量条件为true的所有bean

时间:2014-10-17 16:04:43

标签: java jpa objectdb

我想打印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

2 个答案:

答案 0 :(得分: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));

答案 1 :(得分:-1)

您可以在Person类中添加toString方法并添加其中的所有属性,然后打印该对象。