嗨,我需要使用 and or 条件进行复杂的查询。但 and 条件似乎覆盖了 or 条件,这是我的代码:
public List<UtenteEntity> search(CartesioPojo params) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<UtenteEntity> q = cb.createQuery(UtenteEntity.class);
Root<UtenteEntity> c = q.from(UtenteEntity.class);
UtenteParams utente = (UtenteParams) params;
List<Predicate> p = new Vector<Predicate>();
if(utente.getUsername() != null && !utente.getUsername().equals(""))
p.add(cb.equal(c.get("username"), cb.literal(utente.getUsername())));
if(utente.getCognome() != null && !utente.getCognome().equals(""))
p.add(cb.and(cb.equal(c.get("cognome"), cb.literal(utente.getCognome()))));
if(utente.getRoles() != null && !utente.getRoles().isEmpty()) {
for (RuoloEntity ruolo : utente.getRoles()) {
p.add(cb.or(cb.equal(c.get("ruolo"), cb.literal(ruolo))));
}
}
q.where(p.toArray(new Predicate[p.size()]));
q.orderBy(cb.asc(c.get(USERNAME_COLUMN)));
TypedQuery<UtenteEntity> query = entityManager.createQuery(q);
List<UtenteEntity> result = query.getResultList();
return result;
}
这是我执行此方法时的控制台输出:
executing prepstmnt 2471808 SELECT t0.SEQU_LONG_ID, t0.DATA_AGGIORNAMENTO,
t0.DATA_CREAZIONE, t0.FK_UTENTE_AGGIORNAMENTO, t0.FK_UTENTE_CREAZIONE, t0.COGNOME,
t0.FLAG_DISABILITATO, t0.NOME, t0.PASSWORD, t1.SEQU_LONG_ID, t1.DATA_AGGIORNAMENTO,
t1.DATA_CREAZIONE, t1.FK_UTENTE_AGGIORNAMENTO, t1.FK_UTENTE_CREAZIONE, t1.CODICE,
t1.DESCRIZIONE, t0.USERNAME FROM UTENTE t0, RUOLO t1 WHERE
(t0.FK_RUOLO = ? AND t0.FK_RUOLO = ?) AND t0.FK_RUOLO = t1.SEQU_LONG_ID(+)
ORDER BY t0.USERNAME ASC [params=?, ?]
最佳答案
对于谓词列表,您将在循环中添加包含单个元素的 or 子句:
p.add(cb.or(cb.equal(c.get("ruolo"), cb.literal(ruolo))));
您想要创建一个用 or 连接的谓词列表,并将这个长 or
谓词添加到主列表中:
List<Predicate> disjunction = new ArrayList<Predicate>();
for (RuoloEntity ruolo : utente.getRoles()) {
disjunction.add(cb.equal(c.get("ruolo"), cb.literal(ruolo)));
}
p.add(cb.or(disjunction.toArray(new Predicate[disjunction.size()])));
关于java - openjpa 标准构建器和或,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18012155/