gpt4 book ai didi

java - 选择成员变量条件为真的所有bean

转载 作者:行者123 更新时间:2023-11-30 11:13:27 26 4
gpt4 key购买 nike

我想打印出所有isFoo == truePerson 对象。我不知道如何为 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

最佳答案

尝试:

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

关于java - 选择成员变量条件为真的所有bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26429041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com