Выбрать все bean-компоненты, где условие переменной члена истинно

Я хотел бы распечатать все 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 ответа

Решение

Пытаться:

  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));

Вы можете добавить метод toString в свой класс Person и добавить все атрибуты в нем, а затем распечатать объект.

Другие вопросы по тегам