Java,CriteriaBuilder,使用可选参数“ where”进行查询

问题描述 投票:0回答:1

我必须重写一些代码,但无法在Internet上找到正确的信息。原始部分如下所示:

String query = "select * from sublog_type_map_v where 1 = 1";
if (responsibleGroupId != null && responsibleGroupId.length() != 0 && !responsibleGroupId.equals("0")) {
    query += " and responsible_group_id = " + responsibleGroupId;
}
if (categoryId != null && categoryId.length() != 0 && !categoryId.equals("0")) {
    query += " and category_id = " + categoryId;
}
if (typeId != null && typeId.length() != 0 && !typeId.equals("0")) {
    query += " and type_id = " + typeId;
}
if (subtypeId != null && subtypeId.length() != 0 && !subtypeId.equals("0")) {
    query += " and subtype_id = " + subtypeId;
}

并且我已经进行了此代码:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<SublogTypeMapV> query = builder.createQuery(SublogTypeMapV.class);
Root<SublogTypeMapV> root = query.from(SublogTypeMapV.class);
query.select(root).where(builder.equal(root.get("responsibleGroupId"), responsibleGroupId));

但是使用“ if”表达式以及其他三个参数(稍后将添加)将其视为“可选”。我不知道该怎么做,有人可以帮我吗?

java java-ee criteria
1个回答
0
投票

我想这会做必要的-

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<SublogTypeMapV> query = builder.createQuery(SublogTypeMapV.class);
Root<SublogTypeMapV> root = query.from(SublogTypeMapV.class);
query = query.select(root);
if("some boolean expression") {
    query = query.where(builder.equal(root.get("responsibleGroupId"), responsibleGroupId));
}

您可以在内部处理其他条件。

© www.soinside.com 2019 - 2024. All rights reserved.