我有一个Java文件,查询数据,我试图添加一个过滤功能。通过使用条件构建器和条件查询,我设法获取要过滤的数据。条件查询没有获取数据时添加或条件
作为起动,这是我的显示数据的列:
Name Host
Fikrie ubuntu
Fikrie2 unix
Fikrie3 ulalala
Fikrie4 ugagaga
这里有使用3变量。名称列显示来自名称的数据。对于主机列,这有点棘手。它将显示主机名,但是如果有logAsHost显示,这些数据将覆盖主机名。
所以这是我的数据是如何真正的样子:
Name Host
Fikrie ubuntu <-- hostname = 1, logAsHost = ubuntu
Fikrie2 unix <-- hostname = 123, logAsHost = unix
Fikrie3 ulala <-- hostname = ulala, logAsHost = no value
Fikrie4 ugaga <-- hostname = ugaga, logAsHost = no value
当我试图筛选仅1变量,我能做到这样。 (例如按名称过滤)。当我试图滤除2个变量时,就会出现问题。我没有设法得到任何数据。
这是我使用的代码:
public List<Connection> retrieveAll(String nameFilter, String hostFilter,
int start, int length) {
ServiceUtil.requireAdmin();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Connection> q = cb.createQuery(Connection.class);
Root<Connection> c = q.from(Connection.class);
q.select(c);
logger.info("nameFilter = [" + nameFilter + "]");
logger.info("hostFilter = [" + hostFilter + "]");
//This is the line that I use to query data.
//when I replace Connection_.hostname with Connection_.logAsHost, or Connection_.name
//It works just fine. So I use either one of these line to query.
//q.where(cb.like(c.get(Connection_.hostname), "%" + hostFilter + "%"));
//q.where(cb.like(c.get(Connection_.logAsHost), "%" + hostFilter + "%"));
//q.where(cb.like(c.get(Connection_.name), "%" + nameFilter + "%"));
//This is the problem part.
//When I add cb.or, it cannot get any data.
//From the documentation, it should just be q.where(cb.or(A, B))
//Where A is the first expression and B is the second.
// I have confirm both the expression are working by calling it separately
q.where(cb.or(cb.like(c.get(Connection_.hostname), "%" + hostFilter + "%")), cb.like(c.get(Connection_.logAsHost), "%" + hostFilter + "%"));
List<Connection> results = em.createQuery(q).setFirstResult(start)
.setMaxResults(length).getResultList();
for (Connection conn : results) {
logger.info("Name=" + conn.getName() + ", hostname=["
+ conn.getHostname() + "]" + ", logAsHost =["
+ conn.getLogAsHost() + "]");
}
return results;
}
这个日志表明该数据是否可用:
我用c.get(Connection_.hostname)
,并通过u
到hostFilter,
INFO nameFilter = []
INFO hostFilter = [u]
INFO Name=fikrie3, hostname=[ulala], logAsHost =[]
INFO Name=testt, hostname=[ugaga], logAsHost =[]
我使用了c.get(Connection_.logAsHost)
,并将u
传递给hostFilter,
INFO nameFilter = []
INFO hostFilter = [u]
INFO Name=fikrie, hostname=[192.168.56.90], logAsHost =[ubuntu]
INFO Name=fikrie2, hostname=[192.168.56.90], logAsHost =[unix]
我结合了,并通过u
到hostFilter,
INFO nameFilter = []
INFO hostFilter = [u]
我假设cb.or()
导致此错误。如果是这样,我如何在criteriaquery中正确使用OR条件?我正在按照文档中的这一部分 or(Expression<java.lang.Boolean> x, Expression<java.lang.Boolean> y)
。